[gambit-list] Structs in FFI

James Long longster at gmail.com
Fri Jul 25 11:12:23 EDT 2008

>> Two, am I missing something when it comes to interfacing with C
>> structs?
> I don't know what is best to do when you need to deal with structs,  
> as it is no
> very friendly to do so in gambit's ffi. What i usually to would be  
> to have some
> c-lambda's that will get what I need to be done. Ex:
> (define SDL_Rect:x (c-lambda ((pointer "SDL_Rect")) int16 "___result  
> = ___arg1.x;"))
> (define SDL_Rect:x-set! (c-lambda ((pointer "SDL_Rect") int16) void  
> "___arg1.x =
> ___arg2;"))
> etc...
> This sure is a bit of a pain, and I know there are better ways to do  
> this, but
> they are too much unfriendly for me to use them.

Gambit's FFI is pretty scary at first, because it's basically a low- 
level mechanism for creating your own FFI's.  I think most people  
write a bunch of macros that generate c-lambda's for them.  For  
example, you can write a `define-c-struct' macro that generates the  
appropriate c-lambda's to access structures.  There's probably one on  
the mailing list somewhere.

This macro would be used like:

(define-c-struct vector
   (x int)
   (y int))

and would generate something like (untested):

(c-define-type vector (pointer (struct "vector")))

(define make-vector
   (c-lambda (int int) vector #<<end-code
struct vector *v = (struct vector *)malloc(sizeof(struct vector));
v->x = ___arg1;
v->y = ___arg2;
___result = v;

(define vector-x
   (c-lambda (vector) int "___return = ___arg1->x"))
(define vector-x-set
   (c-lambda (vector int) vector "___arg1->x = ___arg2; ___return =  

(define vector-y
   (c-lambda (vector) int "___return = ___arg1->y"))
(define vector-y-set
   (c-lambda (vector int) vector "___arg1->y = ___arg2; ___return =  

I think there's a way to make Gambit cleanup the object when the  
`foreign' object representing it in scheme land is destructed.  Look  
through the FFI's on the dumping grounds and through the mailing list,  
and you'll probably find some good code to work with the FFI.

Should there be a standard way of doing this in Gambit?  Probably.   
FFI extensions are on the wish list.


More information about the Gambit-list mailing list