c++ - 使用 reinterpret_cast 转换指针的段错误

标签 c++ reinterpret-cast

在下面的 C++ 代码中,我尝试从共享库加载一个函数。

void* tmp = dlsym(dl_lib, symbol);
_fun = reinterpret_cast<plot_sample_fun*>(tmp);

但是,reinterpret_cast 在转换指针时会出现段错误。这里有什么问题?

编辑:

为了提供进一步的上下文,

typedef void plot_sample_fun( const void *, double **, char ***, size_t *);

class Foo {
    void bar(); // Loads _fun as above.

    plot_sample_fun* _fun;
};

最佳答案

指针在物理上只是一个包含一些地址的整数变量。

reinterpret_cast 只是让编译器相信指针是某种类型的技巧。

在上面的代码示例中,段错误的唯一可能性是第一行但作者说是第二行,或者第二行,原因是 _fun 是某种悬挂引用,因此它写入了不正确的内存位置。

在作者更新了指针类型后,我们更清楚正确的代码应该如下所示:

typedef void (plot_sample_fun*)( const void *, double **, char ***, size_t *);

还有作业:

_fun = reinterpret_cast<plot_sample_fun>(tmp);

并且类成员声明不应该有星号*

plot_sample_fun _fun;

如果这没有帮助,那么我们想知道包含 _fun 的类实例是否已正确分配并且尚未释放。

关于c++ - 使用 reinterpret_cast 转换指针的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27047439/

相关文章:

c++ - 括号与花括号

c++ - 如何评估指针和reinterpret_cast?

c++ - reinterpret_cast 用法之间的区别

c++ - 如何从 vector 字符串中获取 union 集的字符串?

c++ - 设置 uchar 的位

c++ - 如何选择阈值自动使用直方图的峰值?

c++ - 通过 C 强制转换访问结构的第一个字段是否违反了严格的别名?

c++ - 如何在非对齐位置将 char 数组转换为 int?

c++ - 我可以在这里使用 reinterpret_cast 吗?

c++ - bazel 创建临时文件失败