Properly shutting down C++ DLL from C# via C interface,

Started by
1 comment, last by texelPerfect 11 years, 7 months ago
Currently I have a C interface between a C++ DLL (DirectX 11 renderer) and a C# program. Everything works fine currently except cleanup. DirectX reports some live buffers in memory on shutdown. To check this, I set break points at the deconstructors of the C++ classes and noted that deconstructors are never called it seems.

I can explicitly get them to run by calling them, however, firstly I do not think this is the cleanest way of doing so, and secondly, I get an error from C# (first chance exepction error), which I assume is because C# is still referencing the C++ DLL.

I'm thinking I should impliment IDisposable (http://msdn.microsof...disposable.aspx) when dealing with the interface but would just like a second-opinion on this matter.

I may just replace the C interface with a C++/CLR wrapper, though the C interface is mostly "working" right now, I just don't like it not cleaning up properly, obviously. smile.png

Btw, the C functions are imported into C# via the standard DllImport operations,
http://msdn.microsof...9(v=vs.71).aspx
Advertisement
.NET doesn't do anything special when it comes PInvoke. You should still get DLL_PROCESS_ATTACH and DLL_PROCESS_DETACH in your DllMain. I guess you can perform clean up using that mechanism.

Other than that, yes, .NET uses the IDisposable interface when dealing with native resources, especially in conjunction with "using". Using is the C# equivalent of C++ destructors - it will call Dispose even if an exceptions is thrown in the using block. The cleanest way is to have something like InitEngine(...) and ShutDownEngine(..) in your C interface, and just wrap those in a disposable object (call Init in constructor and ShutDown in Dispose), creating the object in using. It is really quite similar as to what you'd do in C++ to wrap a C interface. Also, avoid finalizers in C#. Basically, every time you'd need to apply RAII in C#, do it via using + IDisposable. This is usually when you deal with native resources, but it is rarely required in pure .NET code.
Thank you for your advice. biggrin.png

This topic is closed to new replies.

Advertisement