[plt-scheme] scheme_add_managed with FFI

From: Matthew Flatt (mflatt at cs.utah.edu)
Date: Fri Oct 23 08:45:24 EDT 2009

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)


At Wed, 21 Oct 2009 15:09:06 -0600, Chognkai Zhu wrote:
> Matthew told me to change
> 
> (add-managed p (lambda (p _) (my-close p)) #f #f)
> 
> to
> 
> (add-managed p my-close #f #f)
> 
> where my-close lives at top-level so that the lambda won't get garbage 
> collected. I just tried that. No. Segfault still happens. Could anyone 
> (Eli or Matthew) please help again? Many thanks.
> 
> Also, should I make a small example that can reproduce the problem?
> 
> Chongkai
> 
> Chongkai Zhu wrote:
> > Hi all,
> >
> > In one of my programs, I need to use custodian to manage some 
> > resource. So I wrote the following:
> >
> > (define add-managed
> >  (get-ffi-obj "scheme_add_managed" #f
> >               (_fun (_pointer = #f) _scheme (_fun _scheme _pointer -> 
> > _void) _pointer _bool -> _pointer)))
> >
> > ...
> >
> > (add-managed p (lambda (p _) (my-close p)) #f #f)
> >
> > A side note: here p itself is a _pointer (print as #<cpointer>) 
> > returned from some other FFI call.
> >
> > If I run the program for long enough, adding objects under the manage 
> > of custodians, and closing custodians once a while, with other process 
> > (other than PLT) actively using memory, eventually a segfault will 
> > happen when I'm shutdown a custodian (which has some p under it's 
> > management). Testing shows the segfault is related to my 
> > `add-managed', as commenting it the segfault also disappears.
> >
> > I noticed in 
> > http://schemecookbook.org/Cookbook/PLTCustodianRegistration, the FFI 
> > type of scheme_add_managed is different from how I use it. Did I do 
> > something wrong using scheme_add_managed this way? Why does the 
> > segfault happen? Could anyone help elaborate? Thanks in advance.
> >
> > Sincerely,
> > Chongkai
> > _________________________________________________
> >  For list-related administrative tasks:
> >  http://list.cs.brown.edu/mailman/listinfo/plt-scheme
> 
> _________________________________________________
>   For list-related administrative tasks:
>   http://list.cs.brown.edu/mailman/listinfo/plt-scheme


Posted on the users mailing list.