C#调用C++动态链接库(dll)的简单样例
环境:Win10、VS2017
一、生成C++动态链接库dll
-
创建动态链接库dll
-
新建一个C++类
-
打开FourArith.cpp文件,添加四则运算方法
#include “pch.h”
#include “FourArith.h”
extern “C” _declspec(dllexport) double Add(double a, double b);
extern “C” _declspec(dllexport) double Sub(double a, double b);
extern “C” _declspec(dllexport) double Multi(double a, double b);
extern “C” _declspec(dllexport) double Divi(double a, double b);
double Add(double a, double b)
{
return a + b;
}
double Sub(double a, double b)
{
return a - b;
}
double Multi(double a, double b)
{
return a * b;
}
double Divi(double a, double b)
{
if (b != 0) {
return a / b;
}
}
二、新建C#控制台应用,调用上述生成的.dll
-
新建C#控制台应用
-
为了方便.dll的引用,所以将上述的.dll文件复制到当前控制台应用项目的\bin\Debug目录下。
-
导入并调用.dll
[DllImport(“MyDll.dll”, EntryPoint = “Add”, CallingConvention = CallingConvention.Cdecl)]
public static extern double Add(double a, double b);
[DllImport(“MyDll.dll”, EntryPoint = “Sub”, CallingConvention = CallingConvention.Cdecl)]
public static extern double Sub(double a, double b);
[DllImport(“MyDll.dll”, EntryPoint = “Multi”, CallingConvention = CallingConvention.Cdecl)]
public static extern double Multi(double a, double b);
[DllImport(“MyDll.dll”, EntryPoint = “Divi”, CallingConvention = CallingConvention.Cdecl)]
public static extern double Divi(double a, double b);
static void Main(string[] args)
{
double a = 2;
double b = 3;
onsole.WriteLine(Add(a, b));
Console.WriteLine(Sub(a, b));
Console.WriteLine(Multi(a, b));
Console.WriteLine(Divi(a, b));
Console.ReadKey();
}
- 运行查看效果