在非托管回调的委托中抛出异常的含义
在非托管回调期间使用的委托内部引发异常会产生哪些影响或不可察觉的后果?这是我的情况:
非托管 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);
}
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
本机代码将轰炸未处理的异常,然后程序终止。
如果您确实想处理该异常,则需要使用自定义
__try/__catch
关键字 在本机代码中。这是毫无用处的,托管异常的所有详细信息都会丢失。唯一的区别特征是异常代码 0xe0434f4d。由于您无法确切知道出了什么问题,因此也无法可靠地恢复程序状态。最好不要抓住它。或者最好不要扔掉。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.我认为对 COM 对象表示出现异常的正确方法就是返回 HRESULT.E_FAIL。
现在无法测试它,但我认为如果 COM 对象位于另一个进程中,您所要做的就是终止您的进程,并且 COM 对象可能会变得无响应,等待您的代码从回调函数返回(因为您的进程已经死了)。
I think the correct way to say to a COM Object you have an exception is simply to return HRESULT.E_FAIL.
Could not test it right now, but I think that if the COM Object is in another process, all you will do is to kill your process and the COM Object may become unresponsive, waiting for your code to return from the callback function (since your process is dead already).