c++ - 如何从 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;
}
这可以按预期工作,但也感觉有点老套和不安全。我以前从来没有做过这样的事情,所以我在这里做了什么不安全的事情吗?此外,是否有“更好”的方法来做到这一点(例如,我不必再次管理关闭手柄)?这可以被认为是跨操作系统的可移植性吗?
解决方案
Theresdlclose(void *handle)
用于关闭手柄。也更喜欢reinterpret_cast
原始函数指针,而不是 C 样式转换为std::function
.
dlfcn.h
withdlopen
和它的朋友是 POSIX/UNIX API,所以它可能适用于 Solaris、Linux、*BSD、macOS 等。在 Windows上dlysym
相当于GetProcAddress
.<windows.h>
这是一篇关于动态加载的完整文章,可能会有所帮助:https ://en.wikipedia.org/wiki/Dynamic_loading#In_C/C++
推荐阅读
- if-statement - 使用 AND 和 OR 的条件检查失败
- c# - 如何在实体框架中为复合主键的特定列在模型内部创建外键
- android - 在 DB 浏览器 SQLite 上找不到数据库?
- java - 在 Recyclerview Adapter (Android) 中操作数据的位置
- python - 在数学表达式中查找包含在最外层括号内的文本
- android - 如何在单击应用程序图标时关闭画中画活动。我的应用中有多个活动?
- php - 在 mySQL 表中添加时间戳
- javascript - 在 react-native 中管理多个 TextInputs (超过 10+)
- grafana - 如何在 Grafana 中从 Netdata 自定义标签
- go - 关于将“uint8”转换为“int8”的困惑