C++/CLI destructor

c#, c++-cli, destructor

Solution

A C++/CLI destructor is not the same as a C# finaizlier/destructor. A C++/CLR descructor does not override the Finalize() and is not called during garbage collection. C++/CLR has a different syntax to declare a finalizer which would be `MyC++Class::!MyC++Class` in your case.

A C++/CLI destructor is the equivalent of implementing `IDisposable` in C# and in fact does implement `IDisposable`. To call the C++/CLI destructor from C# code you need to call the `Dispose()` method. This is called out explicitly in the C++/CLR documentation.

Problem

I have a mixed language (C#, C++/CLI, native C++) application and I'm tracing the lifetime of some of the objects by putting log statements in constructors and destructors of several objects. I have a C# object that contains a reference to a C++/CLI object. ``` public class MyC#Class { public MyC#Class() { log.Debug("created MyC#Class object " + this.GetHashCode()); } ~MyC#Class() { log.Debug("destroyed MyC#Class object " + this.GetHashCode()); } private MyC++Class myC++Obj = new MyC++Class(); } MyC++Class::MyC++Class() { loggerInt1(LOGDEBUG, "created MyC++Class object %d", (int)this->GetHashCode()); MyC++Class::~MyC++Class() { loggerInt1(LOGDEBUG, "destroyed MyC++Class object %d", (int)this->GetHashCode()); ``` The problem is when the C# object is garbage collected I see the log statement from the C# destructor but I don't see the log statement from the C++/CLI object. In other words I see the "destroyed MyC#Class object XXXX" but I don't see the corresponding "destroyed MyC++Class object YYYY". As I understand it for both C# and C++/CLI the destructors override the Finalize() method that GC would normally call, so the MyC++Class destructor log statement would be printed when the MyC++Class object is garbage collected. Other than the MyC++Class object is being referenced by something else and thus not yet time for GC, does annyone know of any reason why the MyC++Class destructor log statement is not being printed?? Thanks,

Original source