C#调用C++动态链接库(dll)的简单样例

环境:Win10、VS2017


一、生成C++动态链接库dll
1. 创建动态链接库dll

 

 

2. 新建一个C++类

 

 

 

 

3. 打开FourArith.cpp文件,添加四则运算方法

 1 #include "pch.h"
 2 #include "FourArith.h"
 3 
 4 extern "C" _declspec(dllexport) double Add(double a, double b);
 5 extern "C" _declspec(dllexport) double Sub(double a, double b);
 6 extern "C" _declspec(dllexport) double Multi(double a, double b);
 7 extern "C" _declspec(dllexport) double Divi(double a, double b);
 8 
 9 double Add(double a, double b)
10 {
11     return a + b;
12 }
13 
14 double Sub(double a, double b)
15 {
16     return a - b;
17 }
18 
19 double Multi(double a, double b)
20 {
21     return a * b;
22 }
23 
24 double Divi(double a, double b)
25 {
26     if (b != 0) {
27         return a / b;
28     }
29 }

 

 

二、新建C#控制台应用,调用上述生成的.dll
1. 新建C#控制台应用

 

 

2. 为了方便.dll的引用,所以将上述的.dll文件复制到当前控制台应用项目的\bin\Debug目录下。

 

3. 导入并调用.dll

 1 class Program
 2     {
 3 
 4         [DllImport("MyDll.dll", EntryPoint = "Add", CallingConvention = CallingConvention.Cdecl)]
 5         public static extern double Add(double a, double b);
 6         [DllImport("MyDll.dll", EntryPoint = "Sub", CallingConvention = CallingConvention.Cdecl)]
 7         public static extern double Sub(double a, double b);
 8         [DllImport("MyDll.dll", EntryPoint = "Multi", CallingConvention = CallingConvention.Cdecl)]
 9         public static extern double Multi(double a, double b);
10         [DllImport("MyDll.dll", EntryPoint = "Divi", CallingConvention = CallingConvention.Cdecl)]
11         public static extern double Divi(double a, double b);
12 
13         static void Main(string[] args)
14         {
15             double a = 2;
16             double b = 3;
17 
18             Console.WriteLine(Add(a, b));
19             Console.WriteLine(Sub(a, b));
20             Console.WriteLine(Multi(a, b));
21             Console.WriteLine(Divi(a, b));
22             Console.ReadKey();
23         }
24     }

 

posted @ 2021-09-01 11:32  陈金灿  阅读(906)  评论(0)    收藏  举报