[Mono-dev] garbage collection and the embedding API

Paolo Molaro lupus at ximian.com
Wed Oct 31 14:52:39 EDT 2007

On 10/31/07 Sebastian Good wrote:
> What are the lifetime rules for a MonoObject* created with mono_object_new? 
> Is there a corresponding free that needs to be called? I understand that 
> within the JIT's heaps, garbage collection takes care of such issues, but 
> when a CIL pointer "escapes" into the C++ world, I  am having trouble 
> finding documentation describing what to do. I understand it is possible to 
> "pin" these MonoObject*s so they don't move around, but I assume this is 
> unnecessary until a Compacting GC is actually released.

See docs/gc-variables-in-c in the mono directory/svn module.

> Experimentation suggests that one can indeed be careless with these 
> pointers and not suffer a memory leak, but I'd like to have a firm 
> understanding.
> From the discussion at 
> http://www.mono-project.com/Mono:Runtime#Garbage_Collection it seems like  
> the unmanaged C++ heap is not scanned but it seems to me like it is. Does 
> the GC linked in with mono replace the default new() or malloc operators?

Only the stack and the resgisters are scanned in the unmanaged world
(and if it is a thread not created by mono only after you
mono_thread_attach()ed it).
If your only reference to a manged object is somewhere else, including
memory allocated with malloc and new, the GC will free it.
You can use GC handles to cause an object to be kept alive
and you'll have to release it explicitly with mono_gchandle_free().


lupus at debian.org                                     debian/rules
lupus at ximian.com                             Monkeys do it better

More information about the Mono-devel-list mailing list