My Ruby CLR bridge works by creating, on the fly, small CIL shims that invoke the appropriate method(s) on a CLR object. Today I want to talk about how I manage the lifetimes of those CIL shims.
When you execute some code like a = ArrayList.new for the first time, I construct a new ArrayList Ruby class object on the fly. When you execute a method on a class instance such as a.Sort, I construct a CIL shim that knows how to invoke the Sort method on the ArrayList object. That CIL shim is bound to the Ruby class object via a call to rb_define_method.
The CIL shim is created using the DynamicMethod API in CLR 2.0. After I finish defining the body of the dynamic method using my RbDynamicMethod API, I construct a delegate object that represents that method. These delegate objects are eligible for garbage collection, which means that I need to keep a reference to them. Now, when I said that the CIL shim is bound to the Ruby class object, Ruby only knows about the function pointer to the delegate object that represents the CIL shim. That function pointer is only a weak reference to the delegate, which means that it cannot keep the delegate object from being collected by the CLR GC.
To work around this problem, I’ve added a List<Delegate> object to the Ruby class object. Its job is to hold onto references to all of the dynamically created CIL shim delegate objects for that class. When the Ruby class object is garbage collected by Ruby’s GC, my automagical object reference cleanup code will Free the GCHandle object that I use to keep a reference to the List<Delegate> object.
I actually had a far more complicated and convoluted mechanism for dealing with this problem in my initial implementation of the bridge. I’m much happier with the simplicity of this approach in V2.