参考文档:https://www.cnblogs.com/sleepwalker/p/5016610.html
定义动态链接库函数(_stdcall 通用Pascal程序的缺省调用方式):
#include "stdafx.h"
#include <iostream>
using namespace std;
#define LIB_EXPORT 1
#if LIB_EXPORT
#define LIB_DLL extern "C" _declspec(dllexport)
#else
#define LIB_DLL extern "C" _declspec(dllimport)
#endif
//可以将声明和定义写在同一个位置上
LIB_DLL bool _stdcall can_test(std::string& sn,std::string& ipAddr, int& port)
{
return false;
}
def文件的主要作用为解决使用stdcall方式后函数名被改变的问题。
LIBRARY
EXPORTS
can_test @ 1
C++显示调用dll方式
#include <Windows.h>
#include <iostream>
using namespace std;
int main(){
//此处函数指针定义中 _stdcall 非常重要,若不加上这个的话,会导致程序崩溃
typedef bool(_stdcall *pCanTest)(std::string&,std::string&,int&);
HMODULE hDll=LoadLibrary("AtxSharedDll.dll");
if(hDll!=NULL){
pCanTest can=(pCanTest)GetProcAddress(hDll,"can_test");
if(can!=NULL){
string a="1234";
string b="3456";
int port=2345;
std::cout<<can(a,b,port)<<std::endl;
}
else{
std::cout<<"fail find func"<<std::endl;
}
}else{
std::cout<<"fail load dll"<<std::endl;
}
FreeLibrary(hDll);
getchar();
return 0;
}
程序运行后截图:
另一种调用方式:_cdecl。
此方式是C/C++的默认调用方式,只需要将源文件中的_stdcall去掉即可,此方式也不需要.def文件,若只是给C/C++调用的,此方式更加简洁。
至此,C++动态链接库的定义和使用书写完毕。