C# – How to deterministically dispose of a managed C++/CLI object from C#

cc++-cliinterop

I have a managed object in a C++/CLI assembly. Being C++/CLI, it implements the Disposable pattern through its "destructor" (yes, I'm aware it's not the same as a standard C++ destructor). From C++/CLI, I would simply delete the object. However, I am using this object as a member variable in a C# class.

From my C# class, then, I would like to call the equivalent of the Dispose() method on the C++/CLI object when I am finished using it. Since it is (and must be) a member variable of the class, utilizing a using() block is out of the question. As far as I can tell, there is no exposed method for direct, deterministic disposal of resources from a language other than C++/CLI. How can I accomplish this?

Best Answer

It is not so obvious in C++/CLI but it works exactly the way it does in C#. You can see it when you look at the class with Object Browser. Or a decompiler like ildasm.exe, best way to see what it does.

When you write the destructor then the C++/CLI compiler auto-generates a bunch of code. It implements the disposable pattern, your class automatically implements IDisposable, even though you didn't declare it that way. And you get a public Dispose() method, a protected Dispose(bool) method and an automatic call to GC::SuppressFinalize().

You use delete in C++/CLI to explicitly invoke it, the compiler emits a Dispose() call. And you get the equivalent of RAII in C++/CLI by using stack semantics, the compiler automatically emits the Dispose call at the end of the scope block. Syntax and behavior that's familiar to C++ programmers.

You do the exact same thing you'd do in C# if the class would have been written in C#. You call Dispose() to invoke explicitly, you use the using statement to invoke it implicitly in an exception-safe way.

Same rules apply otherwise, you only need the destructor when you need to release something that is not managed memory. Almost always a native object, the one you allocated in the constructor. Consider that it might not be worth the bother if that unmanaged object is small and that GC::AddMemoryPressure() is a very decent alternative. You do however have to implement the finalizer (!ClassName()) in such a wrapper class. You cannot force external client code to call Dispose(), doing so is optional and it is often forgotten. You don't want such an oversight to cause an unmanaged memory leak, the finalizer ensures that it is still released. Usually the simplest way to write the destructor is to explicitly call the finalizer (this->!ClassName();)