[racket] FFI Pointing to racket objects

From: Jay McCarthy (jay.mccarthy at gmail.com)
Date: Mon Mar 4 08:35:03 EST 2013

I wrote an FFI for Chipmunk once:

https://github.com/jeapostrophe/chipmunk/blob/master/chipmunk-ffi.ss

I used _pointer rather than _racket for my body data.

My understanding is that in your version, the Racket object is only
available via the Chipmunk/C data structure, which the GC views as
opaque, so it is collected. If you want to put Racket things in C
objects, you'll have to make sure they are retained on the Racket
side, by (for example), also storing them in a hash table and
monitoring access to the C objects.

Jay



On Sat, Mar 2, 2013 at 8:35 AM, Sam Vervaeck <vervaeck.sam at skynet.be> wrote:
> Hi,
>
>
>
> I am forking an FFI library for physics simulation on Github
> (https://github.com/samvv/Rhipmunk-Physics) but I got stuck with storing
> racket objects in the library’s native structs. From the library’s website:
> http://chipmunk-physics.net/release/Chipmunk-6.x/Chipmunk-6.1.2-API-Reference/group__cp_body.html.
> Here’s the part of the code that needs to be changed:
>
>
>
> (define _cpDataPointer _racket)
>
> (define-cstruct _cpBody
>
>>
>     [data _cpDataPointer] ; user-defined data, like a game object
>
>     …)
>
>
>
> In the following test everything seems to work as expected:
>
>
>
> (define body1 (cpBodyNew 1.0 1.0))
>
> (set-cpBody-data! body1 "This is a test")
>
> (display (cpBody-data body1))
>
>> “This is a test”
>
> (set-cpBody-data! body1 (cons 1 2))
>
> (display (cpBody-data body1))
>
>> (1 . 2)
>
>
>
> However, when I run the following code:
>
>
>
> (collect-garbage)
>
> (display (cpBody-data body1))
>
>
>
> Something goes wrong internally. Sometimes DrRacket crashes, sometimes it
> returns values like #<bad-value>. I have looked into (malloc-immobile-cell
> v) and (free-immobile-cell cptr) but I am not sure that fiddling with the
> memory is such a good idea. Could you please give me any guidelines or point
> me to a procedure I can use to provide this functionality?
>
>
>
> Thanks,
>
>
>
> Sam
>
>
> ____________________
>   Racket Users list:
>   http://lists.racket-lang.org/users
>



--
Jay McCarthy <jay at cs.byu.edu>
Assistant Professor / Brigham Young University
http://faculty.cs.byu.edu/~jay

"The glory of God is Intelligence" - D&C 93


Posted on the users mailing list.