如何从 C++ 调用动态库函数? [英] How to call dynamic library function from c++?

查看:57
本文介绍了如何从 C++ 调用动态库函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我正在创建某种插件系统.我的程序编写代码,然后编译(另见我的 其他 问题).然后使用 dlopen 再次打开生成的(编译的)库.这允许人们自己在程序中编写自定义函数.

Currently I'm creating some sort of plugin system. My program writes the code, which is then compiled (see also my other question). The resulting (compiled) library is than opened again using dlopen. This allows people to program custom functions in the program themselves.

//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;
}

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

This works as expected, but also feels sort of hacky and unsafe. I've never done anything like this before, so am I doing anything unsafe here? Also, is there a "better" way to do this (e.g. where I don't have to manage closing the handle again)? Could this be considered portable across OSes?

推荐答案

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

Theres is dlclose(void *handle) for closing a handle. Also prefer reinterpret_cast to a raw function pointer, instead of C-style casting to an std::function.

dlfcn.hdlopen 和它的朋友是 POSIX/UNIX API,所以它可能适用于 Solaris、Linux、*BSD、macOS 等.在 Windows 上dlysym 的等价物是 中的 GetProcAddress.

dlfcn.h with dlopen and its friends is POSIX/UNIX API, so it will probably work on Solaris, Linux, *BSD, macOS etc. On Windows the equivalent of dlysym is GetProcAddress in <windows.h>.

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

Here a is a full article about dynamic loading thal'll probably help: https://en.wikipedia.org/wiki/Dynamic_loading#In_C/C++

这篇关于如何从 C++ 调用动态库函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆