开发者

How to use DllImport with interfaces in C#?

开发者 https://www.devze.com 2023-02-21 22:04 出处:网络
I have several DllImports with respect to user32.dll in my code and I thought them to be declared in an interface. But that gives me errors saying public, static, extern are not valid with each item.

I have several DllImports with respect to user32.dll in my code and I thought them to be declared in an interface. But that gives me errors saying public, static, extern are not valid with each item.

Example interface code is as follows:

public interface IWindowsFunctions
{
   [DllImport("user32.dll", CharSet = CharSet.A开发者_高级运维uto, SetLastError = true)]
   static extern int MessageBox(int hWnd, string msg, string title, uint flags);
}

Is there any specific way of using this in an interface, or is there an alternative or is it impossible with an interface?

Thanks


Well its already been mentioned many times now that a DLLImport is an implementation, and therefore cannot be defined on an interface, but I thought it would still be worth mentioning that normally I group by DLLImports into a "NativeMethods" class for organisation, like so:

internal static class NativeMethods
{
    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern int MessageBox(int hWnd, string msg, string title, uint flags);
}

Example use:

NativeMethods.MessageBox(myWnd, "Hello World", "Hello", flags);


It's already implemented - the implementation is found in user32.dll. That's what the extern keyword means:

The extern modifier is used to declare a method that is implemented externally.

Interfaces can only declare instance methods for their implementors; as such the static keyword is not valid here either.

Lastly, an interface can't declare implementations; only its implementors can. In this case, since the implementation already exists, it makes no sense to create an interface for it.

If you're looking to create a wrapper class for unmanaged calls, see Kragen's answer.


Interface methods cannot have accessibility modifiers, meaning you can't apply any static/extern/public/private/etc decorators to them.

I don't see why you'd want to use an interface for this; it's non-standard and by convention a DllImport method is implementation, which does not belong in an interface.

Instead you can use a static class, or even a struct.


You cannot do that. A DllImport is about implementation, and an interface says nothing about implementation. Also, C# does not have the concept of static interfasces.

You can create an interface with the correct signature, and create a class that implements that interface, if you want.

0

精彩评论

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