[racket] FFI Pointing to racket objects
The data is user-defined so that's why it might change. There's a small bug in the second part of your example but I get the idea. Using ptr-set! directly gives me the same problem with the garbage collector, probably because it isn't pointing to an immobile cell anymore. Wrapping it up with a 'malloc-immobile-cell' makes everything work. Here's a full example if anyone's interested:
(define (cpBodyGetData cpBody) ; get the contents of the old cell
(ptr-ref (cpBody-data cpBody))
(define (cpBodySetData cpBody val) ; change it to a new cell
(free-immobile-cell (cpBody-data cpBody))
(set-cpBody-data! cpBody (malloc-immobile-cell val)))
This of course requires that an initial (empty) cell is set when make-cpBody is called, since no predicate is available to test the data pointer.
Thanks again,
Sam
-----Oorspronkelijk bericht-----
Van: Matthew Flatt [mailto:mflatt at cs.utah.edu]
Verzonden: maandag 4 maart 2013 18:26
Aan: Sam Vervaeck
CC: 'users'
Onderwerp: Re: [racket] FFI Pointing to racket objects
At Mon, 4 Mar 2013 18:06:10 +0100, "Sam Vervaeck" wrote:
> Just one more question: when implementing malloc-immobile-cell and
> free-immobile-cell, how do you check if a pointer has not yet been
> set? Doing things like:
>
> (if (cpBody-data body1)
> "I have some data"
> "I have nothing")
>
> Always shows "I have nothing".
I expected that the `data' field would have an immutable-cell value --- which might contain #f but not be #f itself --- so I expected "I have some data" always.
You should use `ptr-ref' and `pre-set!' to get or change the value in an immobile cell. Here's an example transcript:
> (define-cstruct _cpBody ([data _racket]))
> (define b (make-cpBody (malloc-immobile-cell #f)))
> (cpBody-data b) #<cpointer>
> (ptr-ref (cpBody-data b) _racket) #f
> (ptr-set! (cpBody-data b) _racket 'something)
> (collect-garbage)
> (ptr-ref (cpBody-data b) _racket) 'something