使用LoadLibrary函数来加载dll库
首先在一个解决方案中创建了三个项目,如下图所示:
DLL_TEST项目的配置类型是exe。另外两个项目的配置类型是dll
三个项目的文件路径排列如下所示:
x64文件夹中是三个项目编译生成的文件所在地。
三个项目中的文件:
Shared_lib.h文件代码如下:
#pragma once #include#include #include class Shared_lib { public: Shared_lib(const char* lib_name); ~Shared_lib(); void* getFunc(const char* func_name); private: const char* m_lib_name; HMODULE m_handle; };
Shared_lib.cpp文件代码如下
#include "Shared_lib.h"
Shared_lib::Shared_lib(const char* lib_name) :
m_lib_name(_strdup(lib_name))
{
if (m_lib_name == nullptr)
{
m_handle = nullptr;
}
else
{
m_handle = LoadLibrary(m_lib_name);
}
}
Shared_lib::~Shared_lib()
{
if (m_handle != nullptr)
{
FreeLibrary(m_handle);
}
if (m_lib_name != nullptr)
{
delete m_lib_name;
m_lib_name = nullptr;
}
}
void* Shared_lib::getFunc(const char* func_name)
{
if (m_handle != nullptr)
{
void* func = GetProcAddress(m_handle, func_name);
return func;
}
return nullptr;
}
调用LoadLibrary函数需要将项目的字符集改成多字节字符集,不然参数无法使用const char*的类型。
main.cpp文件内容:
#include#include "test1.h" #include "Shared_lib.h" using namespace std; int main() { int i; cin >> i; if (i == 1) { printTest1(); } else { typedef void (*print)(); Shared_lib shared_lib("test2.dll"); print p = (print)shared_lib.getFunc("printTest2"); if (p != nullptr) { p(); } } return 0; }
因为main.cpp中使用了test.h,所以需要在DLL_TEST项目中添加这个h文件所在的目录,也要添加test1项目生成的lib目录与test1.lib。
test1.h文件代码如下:
#pragma once #includeusing namespace std; __declspec(dllexport) void printTest1();
需要添加__declspec(dllexport),否则编译完成不会生成.lib文件。
test1.cpp文件代码如下:
#include "test1.h"
void printTest1()
{
cout << "printTest1" << endl;
}
test2.h文件代码如下:
#pragma once #includeusing namespace std; extern "C" __declspec(dllexport) void printTest2();
前面要加extern “C”的关键字,按照C程序来编译这一部分代码。
test2.cpp文件代码如下:
#include "test2.h"
void printTest2()
{
cout << "printTest2" << endl;
}