Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you catch a managed exception (from a delegate) in unmanaged C++?

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?

like image 982
Reddog Avatar asked Nov 06 '22 23:11

Reddog


2 Answers

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

like image 131
Bert Huijben Avatar answered Nov 14 '22 05:11

Bert Huijben


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.

like image 33
Alexandre C. Avatar answered Nov 14 '22 03:11

Alexandre C.