开发者

Is it possible to import a native method in .NET (using the P/Invoke), so that the interop throws Win32Exception automatically?

开发者 https://www.devze.com 2023-02-24 00:47 出处:网络
Numerous Win32 methods use SetLastError to indicate an error. In .NET I would use such a method like so:

Numerous Win32 methods use SetLastError to indicate an error. In .NET I would use such a method like so:

if (!SomeNativeBoolMethod(...))
{
  throw new Win32Exception();
}

OR

var res = SomeNativeIntMe开发者_如何学Cthod(...);
if (res != 0)
{
  throw new Win32Exception(res);
}

I was wondering if the .NET interop infrastructure can do it for me. In this case, I would import SomeNativeBoolMethod and SomeNativeIntMethod as void methods. (For SomeNativeIntMethod this should be optional, depending whether I wish to be able to see the positive return codes or not).

Is it possible?

Thanks.


It sounds like you're looking for a feature similar to the COM interop feature whereby HRESULT signatures are translated into exception throwing methods. If so I'm sorry to say that feature doesn't exist.

Very likely due to the many many different ways with which Win32 APIs report failures. There is simply no universal convention. Unlike COM where there is most definitely a universal convention for anything returning an HRESULT.

The best bet is to introduce a helper function which wraps PInvoke calls and does a check for the error code and throws appropriately.


Have you thought in Aspect Oriented Programming? Maybe you can intercept the calls by using an attribute and then use the generic boilerplate code to throw the exception.

Using .NET infrastructure will be a bit cumbersome, as you will have to:

  1. Create a MarshalByRef or ContextBoundObject derived class
  2. Create instance methods that will perform the interception
  3. Forward the calls to the Win32 imported methods

There are AOP frameworks (Microsoft Policy Injection Application Block, Windsor AOP, ...) that may help you with this.

The other option (which I would try first) is using PostSharp, which can intercept calls to static methods (much better runtime performance that runtime proxies). You can implement your custom attribute, and intercept the Win32 calls, check the GetLastError() and throw an exception if required.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号