gpt4 book ai didi

c++ - 来自 dlsym 的 std::function 导致段错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:46:35 34 4
gpt4 key购买 nike

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

函数.cpp:

#include <array>

#ifdef __cplusplus
extern "C" {
#endif

double function(std::array<double, 1> arg)
{
return arg[0] * 2;
}

#ifdef __cplusplus
}
#endif

ma​​in.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

构建主体:

g++ -Wall -Wextra -g -std=c++17 main.cpp -ldl

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

Native function output: 6
Segmentation fault

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

请帮忙!

最佳答案

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

using function_ptr = double (*)(std::array<double, 1>);
function_ptr function = reinterpret_cast<function_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() 调用 exit 是个坏主意,请改用 return,详细信息可以在这里找到 Will exit() or an exception prevent an end-of-scope destructor from being called?

关于c++ - 来自 dlsym 的 std::function 导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50415323/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com