[plt-scheme] scheme_add_managed with FFI

From: Chognkai Zhu (czhu at cs.utah.edu)
Date: Wed Oct 28 13:48:49 EDT 2009

I still think there is a bug for that:

#lang scheme
(require scheme/foreign
         (only-in '#%foreign ffi-callback))
(provide make-p)
(define callback
  (ffi-callback (lambda (p _) (free p)) (list _scheme _pointer) _void))
(define add-managed
  (get-ffi-obj "scheme_add_managed" #f
               (_fun (_pointer = #f) _scheme _fpointer (_pointer = #f) 
_bool -> _pointer)))
(define (make-p)
 (let ((p (malloc _pointer 'raw)))
   (add-managed p callback #t)

First I'm using ffi-callback from '#%foreign to make the callback, cause 
I can't figure out another way to do it so that only one C callback will 
be build. But the doc says "The '#%foreign module is not intended for 
direct use". Second even though the callback is kept in a module top 
level variable, it can/might be GCed when/before the custodian is 
shutdown, as demonstrated by the attached file.


Matthew Flatt wrote:
> Thanks for the concrete example in PR 10538.
> The key feature of that example is that a single Scheme function is
> registered as a callback twice. The default handling of callbacks is
> that only the most recently generated foreign callback is retained with
> the Scheme function used as a callback. So, the second call to
> scheme_add_managed with the same function allows the foreign callback
> generated by the first call to be GCed.
> The simplest solution is to provides a boxed empty list for `#:keep' in
> the callback type:
>   (_fun #:keep (box null) _scheme _pointer -> _void)

-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: demo.plt
URL: <http://lists.racket-lang.org/users/archive/attachments/20091028/7dab306b/attachment.ksh>

Posted on the users mailing list.