[Mono-list] Mixing managed and unmanaged code

Thomas Sondergaard thomas@thomassondergaard.com
Wed, 8 Oct 2003 16:24:00 +0200

I am working on an interop solution between ruby and the .net CLR. Ruby has
a conservative garbage collector that scans the stack for pointers into it's
heap of managed memory (not .net managed, ruby managed). When I mix managed
and unmanaged code I need to make sure that the ruby garbage collector wont
reap ruby objects referenced in managed code and vice versa.

Objects are passed both ways from ruby to .net and the other way
by-reference using proxies. These proxies use GCHandle's and the ruby
equivalent of CGHandle. However inside the marshalling and interfacing code
I manipulate ruby objects using managed code like in the send() method
below, which is used to invoke ruby methods on a ruby object from

public class Object {

    public Object(IntPtr handle) {
        _handle = handle;

    ~Object() {

    public virtual object send(string cmd, object[] args) {
        IntPtr args = Marshal.arrayFromDotNet(argsArray);
        return Marshal.toDotNet(RubyAPI.rb_apply(_handle,
RubyAPI.rb_intern(cmd), args));

    private IntPtr _handle;


Now here is the real question: Is the 'args' IntPtr in the send() method
above allocated on the stack, so I can be sure that the ruby gc wont collect
the value referenced? Incidently, do you reckon this will be the case for
Microsofts CLR (too)?

Is there some magic in the way that managed and unmanaged code is mixed? It
executes on the same stack, right?

Thank you!

Thomas Sondergaard