背景
POSIX standard在C语言中加入了很多库函数和其他标识符。在 dlsym()
的描述中功能,它说(我强调):
SYNOPSIS
#include <dlfcn.h> void *dlsym(void *restrict handle, const char *restrict name);
DESCRIPTION
The dlsym() function shall obtain the address of a symbol (a function identifier or a data object identifier) ...
C 标准不保证函数指针可以转换为 void *
,甚至指针的大小是相同的。这有效地增加了对 C 类型系统的额外限制。
问题
我的问题是:
- C 的类型系统的这种限制是否有规范 引用,还是只能从某些库函数的描述中推导出来?
- POSIX 甚至可以在
sizeof (<i>function pointer</i>) > sizeof (void *)
的系统上实现吗? ?
引用资料
- C11 标准(最终公开草案):n1570
- 来自 The Open Group 的 POSIX 标准: POSIX.1-2008
- POSIX
dlsym()
function
最佳答案
dlsym() reference说转换不是由 C 标准定义的,但是符合要求的实现必须使它正常工作。因此,在无法使其工作的系统上,这将不是一个符合标准的实现,并且可能会记录这一点:
Note that conversion from a void * pointer to a function pointer as in:
fptr = (int (*)(int))dlsym(handle, "my_function");
is not defined by the ISO C standard. This standard requires this conversion to work correctly on conforming implementations.
C++ perspective 有一篇旧文章谈到这个并链接到旧版本的 dlsym() reference并有更详细的解释:
The ISO C standard does not require that pointers to functions can be cast back and forth to pointers to data. Indeed, the ISO C standard does not require that an object of type void * can hold a pointer to a function. Implementations supporting the XSI extension, however, do require that an object of type void * can hold a pointer to a function. The result of converting a pointer to a function into a pointer to another data type (except void *) is still undefined, however. Note that compilers conforming to the ISO C standard are required to generate a warning if a conversion from a void * pointer to a function pointer is attempted as in:
fptr = (int (*)(int))dlsym(handle, "my_function");
Due to the problem noted here, a future version may either add a new function to return function pointers, or the current interface may be deprecated in favor of two new functions: one that returns data pointers and the other that returns function pointers.
关于c - C 中指针类型的 POSIX 限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27707048/