Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Native and managed destructors

Tags:

c#

c++-cli

I have a native object (C++) that has a gcroot pointer to a managed object (C#).

class SomeNativeClass {
    gcroot<SomeManagedClass ^> managedClass;
};

Question When I delete a native instance of this class in native code delete(someNativeClass) that I previously allocated, will the managedClass instance get garbage collected or should I explicitly delete it (in the native destructor) as well?

like image 637
GETah Avatar asked Jun 16 '12 20:06

GETah


1 Answers

If only delete the native object and the managed is not referenced anywhere else, would it be garbage collected?

That's the essence of garbage collection. The collector destroys an object when it cannot find a reference to the object. It is done a bit differently when you use the gcroot<> template class, the "normal" way the collector finds references to managed objects is by discovering them in cpu registers and the stack of managed code and the managed heap. That can't work in native code, the gcroot<> class helps out.

The gcroot<> constructor calls GCHandle::Alloc() to allocate an explicit reference to the object. Its destructor calls GCHandle::Free() to remove it. Being able to allocate these "tracking handles" is a secondary mechanism in the CLR, it maintains a table for them that the collector consults in addition to references it finds itself.

The net effect is that when your class destructor runs, it will automatically call the gcroot<> destructor. Object reference gone. If that was the only reference, highly likely in this case, the next garbage collection sweep destroys the object. Automatically. Later.

like image 53
Hans Passant Avatar answered Oct 22 '22 12:10

Hans Passant