在非托管回调的委托中引发异常的含义 [英] Implications of throwing exception in delegate of unmanaged callback

查看:170
本文介绍了在非托管回调的委托中引发异常的含义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于在非托管回调的委托中引发异常的含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆