简体   繁体   English

如何在文件之间共享C#DllImport函数?

[英]How can I share C# DllImport functions between files?

I've imported my C++ DLL functions into C# by following some online examples. 我通过以下一些在线示例将C ++ DLL函数导入到C#中。 The functions have to be declared as part of a C# class. 这些函数必须声明为C#类的一部分。 But if I want to use these functions in other C# classes how can I share the declarations? 但是,如果我想在其他C#类中使用这些函数,该如何共享声明?

The best solution would be to import the C++ DLL functions into a general class and use this throughout my application. 最好的解决方案是将C ++ DLL函数导入一个通用类,并在我的整个应用程序中使用它。

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. 编辑:我尝试了下面的建议,但现在我在尝试使用该结构的地方收到错误消息“ ImportSomeStuff由于其保护级别而无法访问”。 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(MyCallback callback);
}

(different file) (不同的文件)

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

They are static functions, so if you make them public you should be able to access them with ClassName.FunctionName() . 它们是静态函数,因此,如果将它们公开,则应该可以使用ClassName.FunctionName()访问它们。 At last that's how you do it with C functions. 最后,这就是使用C函数的方式。

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. 我将其保留在内部互操作程序集内部,并在其之上编写一个公共包装程序,该包装程序更适合C#样式。

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

And then you could call this function from everywhere: 然后您可以从任何地方调用此函数:

Native.SomeFunction();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM