Dll调用有很多方法,这里总结两种比较常用的
(1)会提供三个文件的.lib,.dll,.h,而且采用标准调用的方式
头文件dll1.h
#ifdef DLL1_API
#else
#define DLL1_API extern"C" _declspec(dllimport)
#endif
DLL1_API int _stdcall Test(int a,int b);
源文件dll1.cpp
#include"dll1.h"
#define DLL1_API extern "C" _declspec(dllexport)
DLL1_API int _stdcall Test(int a,int b)
{
return a+b;
}
模块文件 dll1.def
LIBRARY dll1
EXPORTS
Test
新建一个测试工程,加入头文件dll1.h
将lib库增加到工程内,属性-链接器-输入-添加依赖项--加入dll1.lib
将dll文件放入工程内,项目-属性-c++ -附加包含目录
#include "stdafx.h"
#include "dll1.h"
#include<iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int a=1,b=3;
cout<<"c= "<< Test(1,3)<<endl;
system("pause");
return 0;
}
(2)如果项目需要的动态链接库很多,但是也不是每个链接库内的函数都用到,使用上述的方式会占用很大内存,因此使用动态加载的方法
新建一个测试工程2,将dll1.dll与.exe放入同一个文件夹内
#include "stdafx.h"
#include<iostream>
#include<Windows.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
HMODULE hDLL;//模块句柄
hDLL=LoadLibrary(_T("dll1.dll"));//加载dll
typedef int(_stdcall *ADDPROC)(int a,int b);
ADDPROC test = (ADDPROC )GetProcAddress(hDLL,"Test");//获取地址
if(!test)
{
cout<<"获取函数地址失败"<<endl;
}
else
{
cout<<"c is : "<<test(2,3) <<endl;//调用函数
}
FreeLibrary(hDLL);//释放资源
system("pause");
return 0;
}