[plt-scheme] ffi and register-finalizer

From: Eli Barzilay (eli at barzilay.org)
Date: Fri May 20 13:51:29 EDT 2005

On May 20, Michael Reynolds wrote:
> Jay McCarthy wrote:
> 
> >I'm not sure if this answers your question:
> >
> >1. Pointers returned by (malloc) are garbage collected by the
> >   system.

Clarification: pointers that you get from `malloc' *in Scheme* without
the 'raw flag are actually created by the C `scheme_malloc' which will
be collected automatically.  If you're interfacing C code that uses
`malloc' then you do need to take care of them.


> >2. Pointers returned by the library you are interfacing need
> >   finalizers.
> >
> >I'm not if when pointers of type 1 have finalizers they are
> >actually called.

They are -- they are called for any Scheme values that are collected.


> >And remember, garbage collection does not happen as soon as it can
> >(i.e. once lexical scope is gone), but when the GC decides to run.

Yes.  As in my example, you can use `collect-garbage' to trigger a GC
manually.


> So my pointers are not created by malloc, and they are (hopefully)
> registered using the code
> 
> (register-finalizer ptr destructor ) 
> 
> where the destructor is a function that will correctly delete them.
> It seems to me that GC decides not to ever run the finalizer's, is
> that possible?  [...]

No.  Like I said, this should work with any Scheme values.  You should
check that there are no places that keep references to these objects.


> Thanks for letting me know that GC runs when it wants to and not by
> scope, that is good to know and if that is the case perhaps we are
> better off not relying on it anyway.

The whole point of a GC is that it frees you from the burden of
tracking the scope manually.  The problem is that it is a dynamic
scope, so knowing when you should free stuff can become tricky.

-- 
          ((lambda (x) (x x)) (lambda (x) (x x)))          Eli Barzilay:
                  http://www.barzilay.org/                 Maze is Life!



Posted on the users mailing list.