Saturday 16 December 2017

c++ cli - Correct use of IDisposable pattern when using Managed C++ wrapper in C#

itemprop="text">

My C# class creates and uses Managed
C++ object that wraps (allocates and uses) unmanaged C++ objects and resources. The
Managed C++ class correctly implements IDisposable with Destructor and Finalizer.
Therefore, it appears that my C# class should also implement IDisposable. I want to
follow correct IDisposable pattern in C# as
well.



The following is unclear to
me:





  • Within
    Dispose method of my C# class, should I treat my Managed C++ objects as managed or
    unmanaged (since they rely on unmanaged resources internally)?


itemprop="text">
class="normal">Answer



Yes, your
C# class should implement IDisposable as well. Its Dispose() method should simply
dispose the C++/CLI objects. No need for a finalizer, you already implemented one in
your wrappers. Your wrappers are no different from many other .NET classes that wrap an
operating system resource.



For
example:



class Test : IDisposable
{
private CppWrapper obj;

//...
public void
Dispose() {
if (obj != null) {
obj.Dispose();
obj =
null;
}

}
}

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...