If you plan to work in Mono, the answer is simple:
Do not do this
Native methods will no longer execute code, and the exception will be deployed. No cleanup, no C ++ destructors, nothing.
On the other hand, this means that if you are sure that none of the native frames on the stack has any cleanup (if you write code in C ++, it may be more complicated than it seems), then you are free to quit managed exceptions at will.
The reason I so categorically advise doing this is because I once spent two days tracking a memory leak due to handling exceptions that unwind, although native frames. It’s hard to track, and I was stunned for a while (breakpoints weren’t affected, printfs don’t print ... but with the right tools it could take 5 minutes).
If you still decided to throw managed exceptions from your own code, I would do this before returning to managed code:
void native_function_called_by_managed_code () { bool result; if (!result) throw_managed_exception (); }
And I would limit myself to C with these methods, since it is too easy to get into automatic memory management in C ++, which will still leak:
void native_function_called_by_managed_code () { bool result; MyCustomObject obj; if (!result) throw_managed_exception (); }
This can lead to a leak due to the MyCustomObject destructor not being called.
Rolf bjarne kvinge
source share