开发者

How can I share C# DllImport functions between files?

I've imported my C++ DLL functions into C# by following some online examples. The functions have to be declared as part of a C# class. But if I want to use these functions in other C# classes how can I share the declarations?

The best solution would be to import the C++ DLL functions into a general class and use this throughout my application.

Thanks in advance.

Edit: I tried the suggestion below but now I'm getting the error "ImportSomeStuff is inaccessible due to its protection level" where I try to use the struct. Everything seems to be public, so what else can I try?

class ImportSomeStuff
{
    [StructLayout(LayoutKind.Sequential)]
    public struct MyStruct
    {
        public uint nData;
    }

    public delegate void MyCallback(ref MyStruct myStruct);

    [DllImport("My.dll", CallingConvention = CallingConvention.Cdecl)]
    [return: MarshalAs(UnmanagedType.I1)]
    public static extern bool AddCallback(MyCallback callback);

    [DllImport("My.dll", CallingConvention = CallingConvention.Cdecl)]
    [return: MarshalAs(UnmanagedType.I1)]
    public static extern bool RemoveCallback(My开发者_StackOverflowCallback callback);
}

(different file)

class DoSomeStuff
{
    public List<ImportSomeStuff.MyStruct> listStuff = new List<ImportSomeStuff.MyStruct>();
}


public static class Native
{
    [DllImport("nativelib.dll")]
    public static extern int SomeFunction();
}

And then you could call this function from everywhere:

Native.SomeFunction();


They are static functions, so if you make them public you should be able to access them with ClassName.FunctionName(). At last that's how you do it with C functions.

But typically I don't make my native interop stuff public. I keep it internal in my interop assembly and write a public wrapper on top of it which fits C# style better.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜