简体   繁体   English

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

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

I've written a simple C++/CLI DLL that has 2 public static methods:我编写了一个简单的 C++/CLI DLL,它有 2 个公共 static 方法:

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

I'm trying to call these methods from a C# console app in the same solution but the compiler doesn't recognize the methods and shows an error that says that the methods don't "exist in the current context":我正在尝试从同一解决方案中的 C# 控制台应用程序调用这些方法,但编译器无法识别这些方法并显示一个错误,指出这些方法“不存在于当前上下文中”:

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

What is the correct syntax?什么是正确的语法? (online searches have produced pages of irrelevant links with some of the search keywords, assuming DllImport or COM). (假设 DllImport 或 COM,在线搜索产生了带有一些搜索关键字的不相关链接页面)。 This seems like it should be quite a simple matter but finding it is not.这似乎应该是一件很简单的事情,但发现它不是。

Thanks谢谢

First you need build your C++ program, you will get dll.首先你需要构建你的 C++ 程序,你会得到 dll。 Then you should create method with the same return value and add extern key word add DllImport attribute to your method.然后您应该创建具有相同返回值的方法,并将extern关键字添加DllImport属性添加到您的方法中。 In your example method will look like this:在您的示例方法中将如下所示:

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

This should work.这应该有效。 Because the methods are private by default c# wont allow you to access them.因为默认情况下这些方法是私有的,c# 不允许您访问它们。

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

Another way, keeping everything static.另一种方式,保留所有 static。

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

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

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