Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implications of throwing exception in delegate of unmanaged callback

What are the implications or unperceived consequences of throwing an exception inside of a delegate that is used during an unmanaged callback? Here is my situation:

Unmanaged C:

int return_callback_val(int (*callback)(void))
{
  return callback();
}

Managed C#:

[DllImport("MyDll.dll")]
static extern int return_callback_val(IntPtr callback);

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
delegate int CallbackDelegate();

int Callback()
{
  throw new Exception();
}

void Main()
{
  CallbackDelegate delegate = new CallbackDelegate(Callback);
  IntPtr callback = Marshal.GetFunctionPointerForDelegate(delegate);
  int returnedVal = return_callback_val(callback);
}
like image 382
ken Avatar asked Nov 29 '11 18:11

ken


1 Answers

The native code will bomb on the unhandled exception and the program terminates.

If you actually want to handle that exception then you need to use the custom __try/__catch keywords in the native code. Which is pretty useless, all the details of the managed exception are lost. The only distinguishing characteristic is the exception code, 0xe0434f4d. Since you cannot know exactly what went wrong, you cannot reliably restore the program state either. Better not catch it. Or better not throw it.

like image 172
Hans Passant Avatar answered Sep 28 '22 07:09

Hans Passant