Managing destructors of managed (C#) and unmanaged (C++) objects

后端 未结 4 973
轻奢々
轻奢々 2021-01-14 02:46

I have a managed object in a c# dll that maintains an anonymous integer handle to an unmanaged object in a c++ dll. Inside the c++ dll, the anonymous integer is used in an s

4条回答
  •  滥情空心
    2021-01-14 03:16

    You should delete your unmanaged object from the Dipose method of your managed object. You should also call Dispose out of the Finalize method in case your code hasn't called Dispose before the garbage collector got to it. Adam Robinson's answer illustrates that much better.

    So if you are dilligent with you Dispose calls (and use using blocks) you shouldn't have shutdown crashes.

    Edit: I think the problem is actually the unmanaged DLL getting unloaded before the finalizer runs. Ye old "Once the app is shutting down there are no guarantees as to what order the are unloaded".

    Perhaps you can experiment having your unmanaged resources in a managed C++ assembly? That way you know the DLL doesn't go bang before you are finished with it and you don't have to do ugly P/Invoke stuff.

    Here is an example from MSDN:

    ref struct A {
       // destructor cleans up all resources
       ~A() {
          // clean up code to release managed resource
          // ...
          // to avoid code duplication 
          // call finalizer to release unmanaged resources
          this->!A();
       }
    
       // finalizer cleans up unmanaged resources
       // destructor or garbage collector will
       // clean up managed resources
       !A() {
          // clean up code to release unmanaged resource
          // ...
       }
    };
    

    More here http://msdn.microsoft.com/en-us/library/ms177197.aspx

    The above is the same pattern as the C# one except you might get away with having the unamanaged resources in the managed C++ assembly. If you really MUST have those in an unmanaged DLL (not a static unmanaged library) then you are stuck, you will have the same shutdown issues.

提交回复
热议问题