[gambit-list] FFI C struct

Marc Feeley feeley at iro.umontreal.ca
Mon Apr 22 09:09:46 EDT 2013


On 2013-04-22, at 5:37 AM, sales.creditscore at creditscore.co.nz wrote:

> Hi,
> 
> I've spent many many frustrating hours trying to talk to a C struct using the FFI.  Looking around at other examples, there seem to be many ways of doing this..., but none of them worked for me.  In the end I wrote a short example shown below that appears to work.  It relies on all the heavy lifting being done in C and just simple wrappers being written in Scheme. As written, I believe it makes Scheme and C share the same struct, no copies being taken (this is crucial for me, as the C code will alter the C struct and likewise my Scheme code will alter it too).  Before I go too far with this approach, I just want to check that it is memory safe.

As far as I can tell it is memory safe.  However, it might be simpler to put your free_point function as a release function on the Sstruct* foreign type.  That way the free_point function will be called by the Gambit garbage collector when the Scheme program no longer has a reference to a given structure.  If it is possible for your C code to keep pointers to your structure, then it will be convenient to use ___alloc_rc instead of malloc, that way you can increment the reference count in that structure to prevent the garbage collector from freeing the structure.

All of these issues can be abstracted in a macro for defining foreign structures.  This is explained in the following message:

https://mercure.iro.umontreal.ca/pipermail/gambit-list/2009-May/003475.html

Marc




More information about the Gambit-list mailing list