且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C 函数指针转换为 void 指针

更新时间:2022-06-27 00:50:22

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).