环境:Win10、VS2017
一、生成C++动态链接库dll
1. 创建动态链接库dll
2. 新建一个C++类
3. 打开FourArith.cpp文件,添加四则运算方法
4. 生成解决方案,编译生成dll
二、使用C#控制台应用调用上述生成的.dll
1. 新建控制台应用
2. 为了方便调用dll,把MyDll.dll复制到\bin\Debug目录下。
3. 调用MyDll.dll的方法
1 [DllImport("MyDll.dll", EntryPoint = "Add", CallingConvention = CallingConvention.Cdecl)] 2 public static extern double Add(double a, double b); 3 [DllImport("MyDll.dll", EntryPoint = "Sub", CallingConvention = CallingConvention.Cdecl)] 4 public static extern double Sub(double a, double b); 5 [DllImport("MyDll.dll", EntryPoint = "Multi", CallingConvention = CallingConvention.Cdecl)] 6 public static extern double Multi(double a, double b); 7 [DllImport("MyDll.dll", EntryPoint = "Divi", CallingConvention = CallingConvention.Cdecl)] 8 public static extern double Divi(double a, double b); 9 10 static void Main(string[] args) 11 { 12 double a = 2; 13 double b = 3; 14 15 Console.WriteLine(Add(a, b)); 16 Console.WriteLine(Sub(a, b)); 17 Console.WriteLine(Multi(a, b)); 18 Console.WriteLine(Divi(a, b)); 19 Console.ReadKey(); 20 }
4. 运行查看效果