在非托管回调的委托中引发异常的含义

问题描述:

在非托管回调中使用的委托内部引发异常有什么含义或无法预期的后果?这是我的情况:

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:

非托管C:

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

托管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);
}

本机代码将在未处理的异常发生时爆炸,程序终止.

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.