我已经读过将函数指针转换为数据指针,反之亦然,但在大多数平台上都可以工作,但不能保证工作.为什么会这样?两者都不应该只是简单地址到主存储器中,因此兼容吗?
我有一个由dlsym()返回的void指针,我想调用void指针指向的函数.所以我通过强制转换进行类型转换:
void *gptr = dlsym(some symbol..) ;
typedef void (*fptr)();
fptr my_fptr = static_cast<fptr>(gptr) ;
Run Code Online (Sandbox Code Playgroud)
我也试过reinterpret_cast但没有运气,虽然C演员似乎工作..
我试图找出以下前向声明在ANSI-C中是否有效:
第一档:
extern void * fptr; // opaque forward declaration.
int main (void) {
fptr = NULL; // set the function pointer to NULL
}
Run Code Online (Sandbox Code Playgroud)
第二档:
typedef int (*fptr_t)(int);
fptr_t fptr; // real declaration of the function pointer
Run Code Online (Sandbox Code Playgroud)
对我来说,这应该是无效的,因为fptr如果用两种不同的类型声明,但既没有gcc也没有clang给出任何警告.
我会更具体地对C11标准的精确点感兴趣,这些点可以得出结论为什么它有效(或无效).
编辑:在C11标准中,6.2.7:2说:
引用同一对象或函数的所有声明都应具有兼容类型; 否则,行为未定义.
但我找不到如何判断是否void*兼容fptr_t.
我试图返回我调用的函数的地址,例如:
void * myfunctionname(some parameters) {
//some codes
//more codes.
return &myfunctionname;
}
Run Code Online (Sandbox Code Playgroud)
如何用void *正确的类型替换以获得正确的签名?
我在FreeRTOS中使用xTaskCreate,其第四个参数(void*const)是传递给新线程调用的函数的参数.
void __connect_to_foo(void * const task_params) {
void (*on_connected)(void);
on_connected = (void) (*task_params);
on_connected();
}
void connect_to_foo(void (*on_connected)(void)) {
// Start thread
xTaskCreate(
&__connect_to_foo,
"ConnectTask",
STACK_SIZE,
(void*) on_connected, // params
TASK_PRIORITY,
NULL // Handle to the created Task - we don't need it.
);
}
Run Code Online (Sandbox Code Playgroud)
我需要能够传入一个带签名的函数指针
void bar();
但我无法弄清楚如何将void*转换为我可以调用的函数指针.我能得到的最近的是:
错误:'void*'不是第3行的指针对象类型
如何将task_params转换为我可以调用的函数指针?
注意,上面的代码大大简化了.
混淆了如何访问存储在void指针(void*)中的函数指针.
假设你有这个:
void *functions[] =
{
&sqrt, // int ft_sqrt(int nb);
&power,
&logN,
&factorial;
};
// An array of void pointers, each storing a function pointer.
Run Code Online (Sandbox Code Playgroud)
如果我想访问该sqrt功能,我的猜测如下:
(int (*)(int)) functions[0](x)
但我的猜测是错误的:
error: called object type 'void *' is not a function or function pointer
那么如何访问其中一个函数呢?
c pointers function-pointers void-pointers typecasting-operator