Support for structs in FFI on the way

Started by sunmountain, December 08, 2011, 01:31:43 PM

Previous topic - Next topic

sunmountain

Just to give everyone an update:



It is now possible to have arguments and return values as struct types, e.g this is possible:



Here is a small C lib, that uses structs:

#include <stdio.h>

typedef struct clock
    {
    char hour;
    int min;
    short int sec;
    } clock;

clock addClock(clock in)
    {
    in.hour += 1;
    in.min += 1;
    in.sec += 1;
    return in;
    }


Compiling as a DLL and brought to live with;

(struct 'clock "char" "int" "short int")
; struct definition must exist !

(import "struct.dll" "addClock" "clock" "clock")
(set 'fmt "cnnn ld dn")
(set 'in (pack fmt 1 1 1))
(println (unpack fmt in))
(set 'out (addClock in))

; give as string object
(println (unpack fmt out))

; only give address to string
(set 'out (addClock (address out)))
(println (unpack fmt out))
(set 'out (pack fmt 0 0 0))

; repeat
(dotimes (i 100)
    (set 'out (addClock (address out)))
)
(println (unpack fmt out))

; repeat
(dotimes (i 100)
    (set 'out (addClock out))
)
(println (unpack fmt out))

; even fully anonymous calls work !
(println (unpack fmt (addClock (pack fmt 254 (- (pow 2 32) 2) 65534))))

gives this:

(1 1 1)
(2 2 2)
(3 3 3)
(100 100 100)
(-56 200 200)
(-1 -1 -1)


As you can see, right now it is neccessary to pad the struct members manually (n),

here you see the padding on 32 Bit platform (compiled with gcc).



Next step is to extent pack/unpack so that you can do this:



(struct 'clock "char" "int" "short int") ; corresponding to C struct
(import "struct.dll" "addClock" "clock" "clock")
(set 'in (pack clock 1 1 1)) ; auto-boxing
(println (unpack clock in)) ; auto-unboxing -> (1 1 1)
(set 'out (addClock in))
(println (unpack clock out)) ; auto-unboxing -> (2 2 2)


This should be ready before the weekend, I guess.

Lutz

#1
Progress preview of working 'struct' function for the extended libffi API here:



http://www.newlisp.org/downloads/development/inprogress/">http://www.newlisp.org/downloads/develo ... nprogress/">http://www.newlisp.org/downloads/development/inprogress/



Working for 32-bit and 64-bit, little tested, but structure alignment and byte padding seem to work.