Search code examples
c#c++exceptioncallbackpinvoke

Raising exception on managed and unmanaged callback chain with P/Invoke


I am wrapping a native API with P/Invoke calls. For error handling I use the following method:

  • Take a callback function from managed code.
  • Call this callback function from unmanaged code to indicate an error.
  • Throw an exception in the callback.

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.


Solution

  • Short answer: Yes, it is safe.

    Under certain conditions:

    • Unmanaged Function can handle SEH exceptions (C++ can, but C can't)
    • Unmanaged Function will pass the exception to its caller, so its caller must be able to understand and handle the Managed exception (or pass it upper).

    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.