一、 C++调用C++生成的Dll
1. 生成Dll,使用MFC DLL选项生成一个Dll工程
Step 1
在CPP文件中添加
extern "C" int _cdecl Add(int d1, int d2)
{
return d1 + d2;
}
extern "C" int _stdcall Sub(int d1, int d2)
{
return d1 - d2;
}
Step2
在.h文件中添加
#define DllExport extern "C" __declspec(dllexport)
DllExport int _cdecl Add(int d1, int d2);
DllExport int _stdcall Sub(int d1, int d2);
Step3
增加一个给调用者使用的.h文件,在文件中添加
#define DllImport extern "C" __declspec(dllimport)
DllImport int _cdecl Add(int d1, int d2);
DllImport int _stdcall Sub(int d1, int d2);
2. 新建一个普通工程,把之前的.h、.dll、.lib文件拷贝至目标文件夹内
Step1 添加.h文件至工程文件夹中
Step2 将.lib文件引用至工程中
Step3 #include ".h"文件
Step4 调用.h中的函数
二、 C#调用C++生成的Dll
1. 生成Dll,使用MFC DLL选项生成一个Dll工程
Step1
在CPP中添加
extern "C" int _cdecl Add(int d1, int d2)
{
return d1 + d2;
}
extern "C" int _stdcall Sub(int d1, int d2)
{
return d1 - d2;
}
extern "C" int _cdecl Multiple(int a,int b)
{
return a * b;
}
extern "C" int _stdcall Divide(int a,int b)
{
if (b == 0)
{
return 0;
}
else
{
return a / b;
}
}
Step2
在.h中添加
#define DllExport extern "C" __declspec(dllexport)
DllExport int _cdecl Add(int d1, int d2);
DllExport int _stdcall Sub(int d1, int d2);
extern "C" int _cdecl Multiple(int a,int b);
extern "C" int _stdcall Divide(int a,int b);
Step3在.def中添加
EXPORTS
; 此处可以是显式导出
Multiple
Divide
2. 新建一个普通工程,把之前的.h、.dll、.lib文件拷贝至目标文件夹内
Step1
添加一个类,在这个类中将需要用到的函数引用进来
[DllImport("DllExport.dll", EntryPoint = "Add", CallingConvention = CallingConvention.Cdecl)]
public static extern int Add(int a, int b);
[DllImport("DllExport.dll", EntryPoint = "Sub", CallingConvention = CallingConvention.StdCall)]
public static extern int Sub(int a, int b);
[DllImport("DllExport.dll", EntryPoint = "Multiple", CallingConvention = CallingConvention.Cdecl)]
public static extern int Multiple(int a, int b);
[DllImport("DllExport.dll", CallingConvention = CallingConvention.StdCall)]
public static extern int Divide(int a, int b);
Step2
使用新建的类中引入的函数
三、 关于两种调用方式
无论那种调用方式,为了保证生成函数的名称不变化需要加上extern "C"
使用C++调用C++生成的DLL时,这里都是采用的隐式调用方法,使用了extern "C" __declspec(dllexport)和extern "C" __declspec(dllimport)
来调用dll,Add方法使用了_cdecl调用方式,Sub方法使用了_stdcall调用方式
使用C#调用C++生成的DLL时,也是采用了隐式调用方法,除了使用extern "C" __declspec(dllexport)和extern "C" __declspec(dllimport)外
还使用了标准的_cdecl/_stdcall调用方式,使用标准的方式时需要在.def文件中记录使用的函数名称