Support for structs in FFI on the way

Q&A's, tips, howto's
Post Reply
sunmountain
Posts: 39
Joined: Tue Mar 15, 2011 5:11 am

Support for structs in FFI on the way

Post by 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:

Code: Select all

#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;

Code: Select all

(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:

Code: Select all

(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:

Code: Select all

(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
Posts: 5282
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Re: Support for structs in FFI on the way

Post by Lutz »

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

http://www.newlisp.org/downloads/develo ... nprogress/

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

Post Reply