如何在 C++/CLI DLL 中从 C# 应用程序调用函数?

How can I call a function from C# app in a C++/CLI DLL?

我写了一个简单的 C++/CLI DLL,它有 2 个 public 静态方法:

namespace GetMscVerLib
{
    public ref class CGetMscVer
    {
        static System::Int32 GetCompilerVersion ();
        static System::Int32 GetCompilerFullVersion ();
    };
}

我试图在同一解决方案中从 C# 控制台应用程序调用这些方法,但编译器无法识别这些方法并显示一条错误消息,指出这些方法“不存在于当前上下文中” :

namespace Get_MSC_VER
{
    class Program
    {
        static void Main (string[] args)
        {
            Int32 i32CompilerVersion     = CGetMscVer.GetCompilerVersion ();
            Int32 i32CompilerFullVersion = CGetMscVer.GetCompilerFullVersion ();
        }
    }
}

正确的语法是什么? (在线搜索已经产生了与某些搜索关键字无关的链接页面,假设是 DllImport 或 COM)。这看起来应该是一件很简单的事情,但发现它不是。

谢谢

首先你需要构建你的C++程序,你会得到dll。然后你应该创建具有相同 return 值的方法并添加 extern 关键字添加 DllImport 属性到你的方法。在您的示例方法中将如下所示:

public class Program
{
    static void Main(string[] args)
    {
        var version = GetCompilerVersion();
        var fullVersion = GetCompilerFullVersion();
    }
    
    [DllImport("yourDllName.dll")]
    public static extern int GetCompilerVersion();
    
    [DllImport("yourDllName.dll")]
    public static extern int GetCompilerFullVersion();
}

这应该有效。因为默认情况下这些方法是私有的,所以 c# 不允许您访问它们。

namespace GetMscVerLib
{
    public ref class CGetMscVer
    {
      public:
        static System::Int32 GetCompilerVersion ();
        static System::Int32 GetCompilerFullVersion ();
    };
}

另一种方式,让一切保持静态。

// C++/CLI DLL

namespace GetMscVerLib
{
    public ref class CGetMscVer abstract sealed
    {
    public:
        static System::Int32 GetCompilerVersion();
    };
}
// C# assembly that references the C/C++ DLL

namespace Get_MSC_VER
{
    class Program
    {
        static void Main (string[] args)
        {
            Int32 i32CompilerVersion = GetMscVerLib.CGetMscVer.GetCompilerVersion();
        }
    }
}