从类型"void*"到函数指针的强制转换无效

Invalid cast from type ‘void*’ to function pointer

本文关键字:quot 转换 指针 无效 类型 void 函数      更新时间:2023-10-16

我想使用LD_PRELOAD:从libc覆盖open

#include <dlfcn.h>
#include <sys/stat.h>
extern "C" {
int open(const char *path, int flags, mode_t mode)
{
int (*originalOpen)(const char *path, int flags, mode_t mode);
originalOpen = reinterpret_cast<decltype(originalOpen)>(dlsym(RTLD_NEXT, "open"));
//originalOpen = reinterpret_cast<decltype(open)>(dlsym(RTLD_NEXT, "open"));
//...
return (*originalOpen)(path, flags, mode);
}
}

我用g++ -fPIC -shared -o open.so open.cpp -ldl编译。

有人能告诉我为什么上面的代码有效,以及为什么我会出现错误:吗

error: invalid cast from type ‘void*’ to type ‘int(const char*, int, mode_t)’ {aka ‘int(const char*, int, unsigned int)’}
originalOpen = reinterpret_cast<decltype(open)>(dlsym(RTLD_NEXT, "open"));

当我用注释掉的行初始化originalOpen时?

我用的是gcc version 8.0.1

试试这个代码:

originalOpen = reinterpret_cast<decltype(open) *>(dlsym(RTLD_NEXT, "open"));

Decltype获取要创建函数指针时的函数类型。从函数到其类型的指针有隐式转换,但它们并不等价。这就是为什么带有decltype(original_open)的版本工作得很好——original_open的类型是函数指针而不是函数。