首页 > 解决方案 > 如何从 C++ 调用动态库函数?

问题描述

目前我正在创建某种插件系统。我的程序编写代码,然后编译(另见我的另一个问题)。生成的(编译的)库然后使用dlopen. 这允许人们自己在程序中编写自定义功能。

//Open the compiled library at the specified path
void* handle = dlopen("COMPILEDLIBRARYPATH", RTLD_LAZY);
if (handle == NULL) {
    std::cout << "plugin not found" << std::endl;
}

//Find the function pointer and cast is to std::function (is this good practice??)
std::function<void(float[])> fun = (void (*)(float[]))dlsym(handle, "testFunc");
if (fun == NULL) {
    std::cout << "function not found" << std::endl;
}

float test[3] = {0.0, 0.0, 0.0};
std::cout << "calling plugin" << std::endl;
fun(test);

//Output the result of the call
std::cout << test[0] << " " << test[1] << " " << test[2] << " returned by function" << std::endl;

//Close handle again
if (dlclose(handle) != 0) {
    std::cout << "could not close function" << std::endl;
}

这可以按预期工作,但也感觉有点老套和不安全。我以前从来没有做过这样的事情,所以我在这里做了什么不安全的事情吗?此外,是否有“更好”的方法来做到这一点(例如,我不必再次管理关闭手柄)?这可以被认为是跨操作系统的可移植性吗?

标签: c++shared-librariesdlopen

解决方案


Theresdlclose(void *handle)用于关闭手柄。也更喜欢reinterpret_cast原始函数指针,而不是 C 样式转换为std::function.

dlfcn.hwithdlopen和它的朋友是 POSIX/UNIX API,所以它可能适用于 Solaris、Linux、*BSD、macOS 等。在 Windows上dlysym相当于GetProcAddress.<windows.h>

这是一篇关于动态加载的完整文章,可能会有所帮助:https ://en.wikipedia.org/wiki/Dynamic_loading#In_C/C++


推荐阅读