Destructors not called when native (C++) exception propagates to CLR component
- by Phil Nash
We have a large body of native C++ code, compliled into DLLs.
Then we have a couple of dlls containing C++/CLI proxy code to wrap the C++ interfaces.
On top of that we have C# code calling into the C++/CLI wrappers.
Standard stuff, so far.
But we have a lot of cases where native C++ exceptions are allowed to propagate to the .Net world and we rely on .Net's ability to wrap these as System.Exception objects and for the most part this works fine.
However we have been finding that destructors of objects in scope at the point of the throw are not being invoked when the exception propagates!
After some research we found that this is a fairly well known issue. However the solutions/ workarounds seem less consistent. We did find that if the native code is compiled with /EHa instead of /EHsc the issue disappears (at least in our test case it did). However we would much prefer to use /EHsc as we translate SEH exceptions to C++ exceptions ourselves and we would rather allow the compiler more scope for optimisation.
Are there any other workarounds for this issue - other than wrapping every call across the native-managed boundary in a (native) try-catch-throw (in addition to the C++/CLI layer)?