views:

1123

answers:

2

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?

A: 

Catchin 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

Bert Huijben
+1  A: 

One approach would be to use SEH, and do the cleanup in the exception filter before continuing the exception propagation. But I'm not sure that is overly legal since you would be doing a lot of work in the filter. You also wouldn't know anything about the managed exception being propagated.

An alternative is to wrap the managed delegate with your own managed function that catches the exception and in turn throws an unmanaged exception ... which you can then catch in your unmanaged code.

When the unmanaged code has done its cleanup use another helper managed function to re-throw the original managed exception

Rob Walker