Dulini Atapattu
Dulini Atapattu

Reputation: 2735

How to use DllImport with interfaces in C#?

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.Auto, 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

Upvotes: 3

Views: 11036

Answers (4)

BoltClock
BoltClock

Reputation: 724312

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.

Upvotes: 4

Justin
Justin

Reputation: 86779

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);

Upvotes: 10

driis
driis

Reputation: 164341

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.

Upvotes: 1

kprobst
kprobst

Reputation: 16651

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.

Upvotes: 1

Related Questions