使用LoadLibrary函数来加载dll库
首先在一个解决方案中创建了三个项目,如下图所示:
DLL_TEST项目的配置类型是exe。另外两个项目的配置类型是dll
三个项目的文件路径排列如下所示:
x64文件夹中是三个项目编译生成的文件所在地。
三个项目中的文件:
Shared_lib.h文件代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #pragma once #include <cstdio> #include <cstdlib> #include <windows.h> 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文件代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | #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文件内容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | #include<iostream> #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文件代码如下:
1 2 3 4 5 6 7 | #pragma once #include<iostream> using namespace std; __declspec ( dllexport ) void printTest1(); |
需要添加__declspec(dllexport),否则编译完成不会生成.lib文件。
test1.cpp文件代码如下:
1 2 3 4 5 6 | #include "test1.h" void printTest1() { cout << "printTest1" << endl; } |
test2.h文件代码如下:
1 2 3 4 5 6 7 | #pragma once #include<iostream> using namespace std; extern "C" __declspec ( dllexport ) void printTest2(); |
前面要加extern “C”的关键字,按照C程序来编译这一部分代码。
test2.cpp文件代码如下:
1 2 3 4 5 6 | #include "test2.h" void printTest2() { cout << "printTest2" << endl; } |
posted on 2022-02-22 22:54 xcxfury001 阅读(876) 评论(0) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!