C#调用C++编写生成的dll
C++生成dll
- 新建
Win32 console application
,选择生成dll,记得勾选export symbols
,新建空的工程, 添加
GenDll.cpp
的文件,在里面编写内容如下extern "C" __declspec(dllexport) int _stdcall g_Add(int a, int b) { return a + b; } extern "C" __declspec(dllexport) int _stdcall g_Minus(int a, int b) { return a - b; } extern "C" __declspec(dllexport) int _stdcall g_Multi(int a, int b) { return a * b; } extern "C" __declspec(dllexport) int _stdcall g_Div(int a, int b) { return a / b; }
- 在项目的
属性->C/C++->Advanced
中的compile as
中设置为C++,然后编译该项目,在debug文件夹下会生成dll文件,这个dll文件就是之后C#导入函数所需要的文件。 - 注意:
- extern “C”必须加上,否则C#调用时会提示找不到
Entrypoint
- extern “C”必须加上,否则C#调用时会提示找不到
C#调用
将上面生成的
dll
文件拷贝到方便的地方,比如C#debug的目录下,添加一个新的类,用于导入C++中的函数。cs
的具体内容如下:using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.InteropServices; namespace WpfTest { class ReferDll { [DllImport(@"./libs/GenerateDll.dll", EntryPoint = "g_Add")] public extern static int Add(int a, int b); [DllImport(@"./libs/GenerateDll.dll", EntryPoint = "g_Minus")] public extern static int Minus(int a, int b); [DllImport(@"./libs/GenerateDll.dll", EntryPoint = "g_Multi")] public extern static int g_Multi(int a, int b); [DllImport(@"./libs/GenerateDll.dll", EntryPoint = "g_Div")] public extern static int g_Div(int a, int b); } }
- 上面的代码中,
using System.Runtime.InteropServices;
是DllImport
所需要的命名空间。首先传入dll的路径,然后传入具体的函数名。 在其他地方调用时,直接按照下面的方式调用即可
int a = 135; int b = 5; Console.WriteLine("-------------------"); Console.WriteLine(ReferDll.Add(a, b)); Console.WriteLine(ReferDll.Minus(a, b)); Console.WriteLine(ReferDll.g_Multi(a, b)); Console.WriteLine(ReferDll.g_Div(a, b));
- 导入之后的函数名称可以和C++中的函数名不相同