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

时间:2010-12-12 10:00:40

标签: c# dllimport

我已经通过以下一些在线示例将我的C ++ DLL函数导入到C#中。这些函数必须声明为C#类的一部分。但是如果我想在其他C#类中使用这些函数,我该如何共享声明?

最好的解决方案是将C ++ DLL函数导入到通用类中,并在整个应用程序中使用它。

提前致谢。

编辑:我尝试了下面的建议,但现在我收到错误“ImportSomeStuff由于其保护级别而无法访问”,我尝试使用该结构。一切似乎都是公开的,我还能尝试什么?

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

(不同档案)

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

2 个答案:

答案 0 :(得分:3)

它们是静态函数,因此如果您将其公开,则应该能够使用ClassName.FunctionName()访问它们。最后,你就是用C函数做的。

但通常我不会将我的原生互操作内容公之于众。我将它保留在我的interop程序集内部,并在其上面编写一个公共包装器,它更适合C#样式。

答案 1 :(得分:3)

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

然后你可以从任何地方调用这个函数:

Native.SomeFunction();
相关问题