c - C 中指针类型的 POSIX 限制

标签 c posix function-pointers dlsym

背景

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 *) 的系统上实现吗? ?

引用资料

最佳答案

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/

相关文章:

c - 为什么不执行 if 条件?

C 和汇编 __asm 不工作

c - 函数指针中标记之前的预期标识符

c++ - 在函数指针返回值中转换对指针的引用

c++ - 如何在 C/C++ 中收到文件/目录更改的通知,最好使用 POSIX

C++ 指向类方法的指针

将字符串从一个指针复制到另一个指针

c - sscanf 目标地址溢出

c - Pthread不执行函数

c++ - 在信号处理函数中使用本地互斥量来同步共享数据