From: Lyle Johnson Date: 2002-04-11T01:33:38+09:00 Subject: Re: C++ extensions, garbage collection, Ruby and SWIG > The only cases I have found where garbage collection was an issue with > swig were: > > 1) I needed to callback into Ruby code, so I passed in a VALUE > directly to my C++ code. I stored a reference to this VALUE, so I > had to mark it. The CVS version of SWIG (which will be released as SWIG 1.3.12) includes a new %markfunc directive (for the Ruby module only) that lets you specify the name of a C function to be used as the "mark" function for instances of a given class during the garbage collector's "mark" phase. The use of this is partially documented but I haven't gotten back to complete it yet. But the bottom line is that SWIG's can't really tell which Ruby objects are reachable from your wrapped C++ objects and in this case you can give it some help. For Paul's example, he probably wrote a mark function that looked something like this: class MyCppClass { private: VALUE _callbackObj; public: void setCallbackObj(VALUE callbackObj); VALUE getCallbackObj() const; }; %{ void markMyCppClass(void *ptr) { MyCppClass *myCppObj = (MyCppClass *) ptr; rb_gc_mark(myCppObj->getCallbackObj()); } %} With the %markfunc directive, he can tell SWIG to associate the markMyCppClass() function with all new instances of MyCppClass, so that GC is handled properly: %markfunc MyCppClass "markMyCppClass"; > Perhaps Lyle can come up with a couple more cases. I would mainly second what Tobias said in his response to Phil's post, that you've really got to pay attention and understand how the C++ library is doing its "automated garbage collection". From my five-second glance at the BuDDy home page it does indeed sound like they're doing something with reference counting and, presumably, "smart" pointers that do the ref-counting for you.