I want to dynamically link a shared library and assign a function from it to a std::function
. Here is the code:
function.cpp:
#include <array>
#ifdef __cplusplus
extern "C" {
#endif
double function(std::array<double, 1> arg)
{
return arg[0] * 2;
}
#ifdef __cplusplus
}
#endif
main.cpp:
#include <functional>
#include <iostream>
#include <fstream>
#include <array>
#include <functional>
#ifdef __linux__
#include <dlfcn.h>
#endif
int main()
{
void *handle;
double (*function)(std::array<double, 1>);
char *error;
handle = dlopen("/home/oleg/MyProjects/shared_library_test/libFunction.so", RTLD_LAZY);
if (!handle)
{
fprintf(stderr, "%s\n", dlerror());
exit(EXIT_FAILURE);
}
dlerror();
*(void **) (&function) = dlsym(handle, "function");
if ((error = dlerror()) != NULL)
{
fprintf(stderr, "%s\n", error);
exit(EXIT_FAILURE);
}
std::cout << "Native function output: " << function(std::array<double, 1>{ 3.0 }) << std::endl;
dlclose(handle);
std::function<double(std::array<double, 1>)> std_function(*function);
std::cout << "std::function output: " << std_function(std::array<double, 1>{ 3.0 }) << std::endl;
exit(EXIT_SUCCESS);
}
Build shared library:
g++ -Wall -Wextra -g -std=c++17 -shared -o libFunction.so -fPIC function.cpp
Build main:
g++ -Wall -Wextra -g -std=c++17 main.cpp -ldl
Running the program leads to the following output:
Native function output: 6
Segmentation fault
So, as you can see, I successfully compile the library and load it in my main program. However, assigning the function pointer to std::function
doesn't work.
Please, help!
You better do conversion in C++ style:
using function_ptr = double (*)(std::array<double, 1>);
function_ptr function = reinterpret_cast<function_ptr>( dlsym(handle, "function") );
But the culprit is that you cannot call this function directly or indirectly through std::function
wrapper after you close shared library:
dlclose(handle);
// function cannot be used anymore
note it can be better to use RAII for this:
std::unique_ptr<void *,int(void*)> handle( dlopen("/home/oleg/MyProjects/shared_library_test/libFunction.so", RTLD_LAZY), dlclose );
then you do not need to call dlclose()
manually
Note: it is a bad idea to call exit from main()
in C++, use return
instead, details can be found here Will exit() or an exception prevent an end-of-scope destructor from being called?