工程创建
创建动态库工程,添加dllTest.h
#if defined(_MSC_VER) && (_MSC_VER > 1000)
#pragma once
#endif
// 订阅
int _stdcall Subscribe();
// 取消订阅
bool _stdcall UnSubscribe();
添加dllTest.cpp
#include "dllTest.h"
#include <iostream>
using namespace std;
int _stdcall Subscribe()
{
cout << "Subscribe" << endl;
return 0;
}
bool _stdcall UnSubscribe()
{
cout << "UnSubscribe" << endl;
return true;
}
添加Source.def,新增内容如下:
LIBRARY "dllTest"
EXPORTS
Subscribe @1
UnSubscribe @2
整个工程框架如图所示:
隐式调用
方法1
创建控制台应用文件defTest.cpp
#include "dllTest.h"
#include <iostream>
using namespace std;
//隐式调用
int main()
{
Subscribe();
UnSubscribe();
system("pause");
return 0;
}
修改工程属性: 属性-链接器-常规-附加库目录,添加如下:
属性-链接器-输入-附加依赖项,修改如下:
方法2
#include "dllTest.h"
#include <iostream>
using namespace std;
#pragma comment("lib", "..\\Debug\\dllTest.lib")
int main()
{
Subscribe();
UnSubscribe();
system("pause");
return 0;
}
显式调用
#include "dllTest.h"
#include <windows.h>
#include <iostream>
#include <tchar.h>
using namespace std;
typedef int (WINAPI *SubscribeFunc)();
typedef bool (WINAPI *UnSubscribeFunc)();
// 显式调用
int main()
{
HMODULE handle = LoadLibrary(_T("..\\Debug\\dllTest.dll"));
if (nullptr != handle)
{
// 方法1: 从.def中获取@1的方法(获取Subscribe在动态库中的地址)
SubscribeFunc subscribe = (SubscribeFunc)GetProcAddress(handle, (char*)1);
// 方法2: 获取函数名"Subscribe"
//SubscribeFunc subscribe = (SubscribeFunc)GetProcAddress(handle, "Subscribe");
if (nullptr != subscribe)
{
subscribe();
}
UnSubscribeFunc unsubscribe = (UnSubscribeFunc)GetProcAddress(handle, "UnSubscribe");
if (nullptr != unsubscribe)
{
unsubscribe();
}
FreeLibrary(handle);
}
system("pause");
return 0;
}
1)使用LoadLibrary函数加载动态库dll,这里需要注意,如果加载的动态库有依赖其他动态库,需要使用LoadLibraryEx,否则加载失败;
2)获取函数指针的方法有两种。一种是GetProcAddress函数的第二个参数为(char*)1,这里的1对应的是.def中的@1,即获取函数在动态库中的地址。另一种是GetProcAddress函数的第二个参数为函数名。
执行结果如图所示: