I have unmanaged C++ calling a managed delegate via the function pointer provided by Marshal::GetFunctionPointerForDelegate. This delegate has the potential to throw an exception. I need to be able to properly handle this exception in my unmanaged C++ to ensure things like pointer cleanup, and potentially rethrow the exception up into more managed code. The call stack is similar to this:
Managed Code -> Unmanaged C++ -> callback to Managed Code via delegate (exception can be thrown here).
Anyone have pointers for properly handling this situation so that the resources in unmanaged code can be cleaned up and a usable exception can be thrown out to the managed code which initiated the whole call stack?
Catching from managed code with
try
{
throw gcnew InvalidOperationException();
}
catch(InvalidOperationException^ e)
{
// Process e
throw;
}
And an
[assembly:RuntimeCompatibility(WrapNonExceptionThrows = true)];
on your assembly catches managed and unmanaged exceptions
Don't even remotely try to make the "unmanaged" code aware of the fact that it will have to deal with .NET.
Return a non-zero value from your callback to signal the presence of an error. Provide a (thread local) global string object describing the error so that you can retrieve a helpful error message for the user.
This may involve wrapping your delegate into another function under the scenes, which will catch all the exceptions and return the error code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With