How can I deterministically dispose of a managed C++/CLI object from C#?

后端 未结 3 1330
南笙
南笙 2021-02-19 07:26

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

相关标签:
3条回答
  • 2021-02-19 08:12

    The C++/CLI destructor-like syntax automatically implements IDisposable, but it does so in a manner similar to C#'s explicit interface implementation. This means you'll have to cast to IDisposable to access the Dispose method:

    ((IDisposable)obj).Dispose();
    
    0 讨论(0)
  • 2021-02-19 08:20

    You can't. At least, not from C#. Let the garbage collector do its job.

    0 讨论(0)
  • 2021-02-19 08:31

    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();)

    0 讨论(0)
提交回复
热议问题