I am wrapping a native API with P/Invoke calls. For error handling I use the following method:
In other words the flow is like this:
Managed Method => (P/Invoke) Unmanaged Function => Managed Callback => Throw Exception.
When I test this method I can catch the exception successfully in the first managed method. But, I'm not 100% sure that this does not cause any side effects on stack or leak memory.
Is it safe to use this method? If not, is there any other method to indicate error (possibly including stack trace) without cluttering the API using P/Invoke?
P.S. I have access to the native code.
Short answer: Yes, it is safe.
Under certain conditions:
Example, you can't start a new thread and call the managed callback in the new thread, the exception thrown by the callback will certainly terminate you application.