C 函数指针转换为 void 指针 [英] C function pointer casting to void pointer
问题描述
我正在尝试运行以下程序,但遇到一些奇怪的错误:
I am trying to run the following program but getting some strange errors:
文件 1.c:
typedef unsigned long (*FN_GET_VAL)(void);
FN_GET_VAL gfnPtr;
void setCallback(const void *fnPointer)
{
gfnPtr = *((FN_GET_VAL*) (&fnPointer));
}
文件 2.c:
extern FN_GET_VAL gfnPtr;
unsigned long myfunc(void)
{
return 0;
}
main()
{
setCallback((void*)myfunc);
gfnPtr(); /* Crashing as value was not properly
assigned in setCallback function */
}
这里 gfnPtr() 在使用 gcc 编译时在 64 位 suse linux 上崩溃.但它成功调用了 gfnPtr() VC6 和 SunOS.
Here the gfnPtr() is crashing on 64-Bit suse linux when compiled with gcc. But it successfully calling gfnPtr() VC6 and SunOS.
但是如果我按照下面给出的方法更改功能,它就会成功运行.
But if I change the function as given below, it is working successfully.
void setCallback(const void *fnPointer)
{
int i; // put any statement here
gfnPtr = *((FN_GET_VAL*) (&fnPointer));
}
请帮助找出问题的原因.谢谢.
Please help with the cause of problem. Thanks.
推荐答案
C 标准不允许将函数指针强制转换为 void*
.您只能转换为另一种函数指针类型.在 C11 标准,6.3.2.3 §8 中:
The C standard does not allow to cast function pointers to void*
. You may only cast to another function pointer type. In the C11 standard, 6.3.2.3 §8:
指向一种类型的函数的指针可以转换为指向 a 的指针另一种类型和返回的功能再次
A pointer to a function of one type may be converted to a pointer to a function of another type and back again
重要的是,您必须在使用指针调用函数之前转换回原始类型(从技术上讲,转换为兼容类型.6.2.7).
Importantly, you must cast back to the original type before using the pointer to call the function (technically, to a compatible type. Definition of "compatible" at 6.2.7).
请注意 POSIX 标准,许多(但不是全部)C 编译器由于使用它们的上下文也必须遵循该标准,它要求函数指针可以转换为 void*
然后回来.这对于某些系统功能(例如 dlsym
)是必需的.
Note that the POSIX standard, which many (but not all) C compilers have to follow too because of the context in which they are used, mandates that a function pointer can be converted to void*
and back. This is necessary for some system functions (e.g. dlsym
).
这篇关于C 函数指针转换为 void 指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!