.NET PInvoke的异常处理 [英] .NET PInvoke Exception Handling

查看:222
本文介绍了.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?

推荐答案

使用的P / Invoke它可以安全地说有两种需要处理的错误。

With P/Invoke it's safe to say there are two kinds of errors you need to handle.

  1. 例外抛出的P / Invoke本身。
  2. 将DLL的要调用/
  3. 返回的错误

使用1组有一对夫妇可能发生异常(不是最终名单):

With group 1 there are a couple of exceptions that can occur (not the definitive list):

  • EntryPointNotFoundException
  • ExecutionEngineException
  • 的MissingMethodException
  • NotSupportedException异常

使用2组,你需要检查你的P /调用的方法/函数调用的返回结果,并采取适当的行动。 Marshal.GetLastWin32Error()就派上用场了这里。

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.

这就是为什么它总是最好创建包装类需要使用任何原生的东西。这样,你可以在你的返回结果转换为例外和你分开管理和本地code。

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.

这篇关于.NET PInvoke的异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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