在C++中通过封装LoadLibrary/GetProcAddress和dlopen/dlsym实现跨平台动态库加载,Windows使用HMODULE,Linux/Unix使用void*,统一接口支持插件系统。

在C++中实现运行时动态加载库(Windows下的DLL和Linux/Unix下的SO)是一项常见的跨平台需求,比如插件系统或模块化架构。虽然不同操作系统提供的API不同,但可以通过封装统一接口来实现跨平台兼容。
示例代码:
#include <windows.h>
#include <iostream>
<p>typedef int (*AddFunc)(int, int);</p><p>int main() {
HMODULE lib = LoadLibrary(L"example.dll");
if (!lib) {
std::cerr << "无法加载DLL" << std::endl;
return -1;
}</p><pre class='brush:php;toolbar:false;'>AddFunc add = (AddFunc)GetProcAddress(lib, "add");
if (!add) {
std::cerr << "无法获取函数地址" << std::endl;
FreeLibrary(lib);
return -1;
}
std::cout << "结果: " << add(2, 3) << std::endl;
FreeLibrary(lib);
return 0;}
立即学习“C++免费学习笔记(深入)”;
编译时需链接 dl 库:-ldl
#include <dlfcn.h>
#include <iostream>
<p>typedef int (*AddFunc)(int, int);</p><p>int main() {
void* lib = dlopen("./libexample.so", RTLD_LAZY);
if (!lib) {
std::cerr << "无法加载SO: " << dlerror() << std::endl;
return -1;
}</p><pre class='brush:php;toolbar:false;'>AddFunc add = (AddFunc)dlsym(lib, "add");
const char* error = dlerror();
if (error) {
std::cerr << "无法获取函数: " << error << std::endl;
dlclose(lib);
return -1;
}
std::cout << "结果: " << add(2, 3) << std::endl;
dlclose(lib);
return 0;}
立即学习“C++免费学习笔记(深入)”;
#ifdef _WIN32
#include <windows.h>
using LibHandle = HMODULE;
#define LOAD_LIB(name) LoadLibraryA(name)
#define GET_FUNC(lib, name) GetProcAddress(lib, name)
#define FREE_LIB(lib) FreeLibrary(lib)
#else
#include <dlfcn.h>
using LibHandle = void*;
#define LOAD_LIB(name) dlopen(name, RTLD_LAZY)
#define GET_FUNC(lib, name) dlsym(lib, name)
#define FREE_LIB(lib) dlclose(lib)
#endif
<p>class DynamicLib {
public:
explicit DynamicLib(const char* path) {
handle = LOAD_LIB(path);
}</p><pre class='brush:php;toolbar:false;'>~DynamicLib() {
if (handle) FREE_LIB(handle);
}
void* getFunction(const char* name) {
return GET_FUNC(handle, name);
}
bool isValid() const { return handle != nullptr; }private: LibHandle handle = nullptr; };
使用方式:
DynamicLib lib("example.dll"); // 或 libexample.so
if (lib.isValid()) {
auto add = (AddFunc)lib.getFunction("add");
if (add) std::cout << add(2, 3) << std::endl;
}
基本上就这些。只要封装好平台差异,并规范导出接口,C++动态加载库并不复杂,但容易忽略细节导致运行失败。
以上就是c++++怎么在运行时动态加载库(dll/so)_c++跨平台动态链接库加载方法的详细内容,更多请关注php中文网其它相关文章!
.dll文件缺失怎么办?.dll文件在哪下载?不用担心,这里为大家提供了所有的.dll文件下载,无论用户丢失的是什么.dll文件,在这里都能找到。用户保存后,在网盘搜索dll文件全称即可查找下载!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号