且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 C++ 中创建 dll 以在 C# 中使用

更新时间:2022-04-29 05:48:49

评论了几句,这里试试:

After several comments, here a try:

C++ 代码 (DLL),例如.math.cpp,编译成 HighSpeedMath.dll:

C++ Code (DLL), eg. math.cpp, compiled to HighSpeedMath.dll:

extern "C"
{
    __declspec(dllexport) int __stdcall math_add(int a, int b)
    {
        return a + b;
    }
}

C# 代码,例如.程序.cs:

C# Code, eg. Program.cs:

namespace HighSpeedMathTest
{
    using System.Runtime.InteropServices;

    class Program
    {
        [DllImport("HighSpeedMath.dll", EntryPoint="math_add", CallingConvention=CallingConvention.StdCall)]
        static extern int Add(int a, int b);

        static void Main(string[] args)
        {
            int result = Add(27, 28);
        }
    }
}

当然,如果入口点已经匹配,则不必指定它.调用约定也一样.

Of course, if the entry point matches already you don't have to specify it. The same with the calling convention.

正如评论中提到的,DLL 必须提供 C 接口.这意味着,外部C",没有例外,没有引用等.

As mentioned in the comments, the DLL has to provide a C-interface. That means, extern "C", no exceptions, no references etc.

如果您有 DLL 的头文件和源文件,它可能如下所示:

If you have a header and a source file for your DLL, it could look like this:

数学.hpp

#ifndef MATH_HPP
#define MATH_HPP

extern "C"
{
    __declspec(dllexport) int __stdcall math_add(int a, int b);
}

#endif

数学.cpp

#include "math.hpp"

int __stdcall math_add(int a, int b)
{
    return a + b;
}