This is the mail archive of the guile@cygnus.com mailing list for the guile project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: Guile, C, and Garbage Collection


Daniel R Risacher <risacher@worldnet.att.net> writes:
> 
> Now suppose one of your users does something like this:
> 
> (define toplevelfoo (Clib-make-new-foo))
> (let ((temp-bar (Clib-make-new-bar)))
>      (Clib-foo-set-pointer-to-bar toplevelfoo temp-bar))
> (gc)
> 	
> Now, the bar you allocated with Clib-make-bar doesn't have any scheme
> references to it any more, so it gets garbage collected, because the 
> garbage collector doesn't know that there is a pointer to it inside
> toplevelfoo.   And the next time the program tries to look for 
> toplevelfoo->bar it will seg fault.

>From what I can tell, you have three options.

The first is to implement enough knowledge about the C data structures
into the Guile bindings that they can find the bar hanging off of a
foo and mark it too when a foo is marked (during gc).

You need to be able to find the Scheme wrapper from a C pointer, but
maybe you need to do that anyway.

The second option is to implement some kind of reference counting for
the C structures.  Wrapping a pointer to such a structure in a smob
would increment the ref count and freeing the smob would decrease it.
Likewise, storing the pointer anywhere else would have to maintain the
ref count, such as storing a bar pointer into a foo structure.

This prohibits circular references, but it might be more suitable for
a generic memory management interface.  You might want to include it
in the original C library so that everyone can benefit, not just
Guile.

The third option would be to use a C garbage collector.

The first two amount to non-trivial work because you have to
understand the memory mangement issues of the original C library and
maybe hack it to behave sensible.  I'm currently doing it for Gtk and
it is not much fun.