.NET PInvoke 异常处理
使用 PInvoke 时可能会发生哪些异常,或者所有错误均由方法返回值处理,并且由开发人员检查并在需要时引发异常?
What exceptions can occur when using PInvoke or are all errors handled by the method return values and it is up to the developer to check and raise exceptions if needed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对于 P/Invoke,可以肯定地说您需要处理两种错误。
对于第 1 组,可能会发生一些异常(不是最终列表):
对于第 2 组,您需要检查 P/Invoked 方法/函数的返回结果适当地打电话并采取行动。 Marshal.GetLastWin32Error() 在这里派上用场。
这就是为什么最好为您需要使用的任何本机内容创建包装类。这样您就可以将返回结果转换为异常并将托管代码和本机代码分开。
With P/Invoke it's safe to say there are two kinds of errors you need to handle.
With group 1 there are a couple of exceptions that can occur (not the definitive list):
With group 2 you need to check the return result of your P/Invoked method/function call and act appropriately. Marshal.GetLastWin32Error() comes in handy here.
This is why it's always best to create wrapper classes for any native stuff you need to use. That way you can convert your return results to exceptions and separate your managed and native code.
我不确定是否有可以抛出的异常的明确列表,但我知道
这些异常类型中的大多数都不是特定于 PInvoke 的,并且可能发生在程序中的任何点。唯一特定于 PInvoke 调用的是 DLL 未找到异常(我不记得其类型)。
I'm not sure if there is a definitive list of the exceptions that can be thrown, but I know at least the following can occur
Most of these exceptions types are not specific to PInvoke and can occur at any point in the program. The only one specific to the PInvoke call is the DLL not found exception (who's type I can't remember).
另外:
DllNotFoundException
BadImageFormatException
(DLL 格式错误或已损坏)MethodAccessException
(尝试通过安全透明方法调用本机代码)Also:
DllNotFoundException
BadImageFormatException
(DLL is wrong format or corrupted)MethodAccessException
(Attempt by security transparent method to call native code)当进程内存不足时,pinvoke 还会在移动设备上引发
MissingMethodException
: http://www.tomergabel.com/NETCompactFrameworkPInvokeAndMissingMethodException.aspxpinvoke also throws a
MissingMethodException
on mobile devices, when the process is out of memory: http://www.tomergabel.com/NETCompactFrameworkPInvokeAndMissingMethodException.aspx