来自dlsym的std :: function导致分段错误

时间:2018-05-18 16:05:59

标签: c++ linux dynamic-linking std-function dlsym

我想动态链接共享库并将其中的函数分配给std::function。这是代码:

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

构建共享库:

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

运行程序会产生以下输出:

Native function output: 6
Segmentation fault

因此,正如您所看到的,我成功编译了库并将其加载到我的主程序中。但是,将函数指针指定给std::function并不起作用。

请帮忙!

1 个答案:

答案 0 :(得分:5)

你最好用C ++风格进行转换:

using func_ptr = double (*)(std::array<double, 1>);
func_ptr function = reiterpret_cast<func_ptr>( dlsym(handle, "function") );

但罪魁祸首是,在关闭共享库后,您无法通过std::function包装器直接或间接调用此函数:

dlclose(handle);
// function cannot be used anymore

请注意,最好使用RAII:

std::unique_ptr<void *,int(void*)> handle( dlopen("/home/oleg/MyProjects/shared_library_test/libFunction.so", RTLD_LAZY), dlclose );

然后您无需手动调用dlclose()

注意:在C ++中调用main()退出是个坏主意,请改用return,详情请见Will exit() or an exception prevent an end-of-scope destructor from being called?