问题
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?
回答1:
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.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>
.
Here a is a full article about dynamic loading thal'll probably help: https://en.wikipedia.org/wiki/Dynamic_loading#In_C/C++
来源:https://stackoverflow.com/questions/55393629/how-to-call-dynamic-library-function-from-c