.NET PInvoke Exception Handling

后端 未结 4 483
無奈伤痛
無奈伤痛 2020-12-16 20:22

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 ne

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-16 21:11

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

    1. Exceptions thrown by P/Invoke itself .
    2. Errors returned by the dll's you are invoking/

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

    • EntryPointNotFoundException
    • ExecutionEngineException
    • MissingMethodException
    • NotSupportedException

    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.

提交回复
热议问题