POSIX restrictions on pointer types in C

自闭症网瘾萝莉.ら 提交于 2019-12-03 23:57:12

问题


Background

The POSIX standard adds a lot of library functions and other identifiers to the C language. In the description of the dlsym() function, it says (with my emphasis):

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

The C standard doesn't guarantee that a function pointer can be converted to a void *, or even that the size of the pointers are the same. This effectively adds an additional restriction on C's type system.

Question

My question is this:

  • Is there a normative reference for this restriction of C's type system, or is it only deducible from the description of certain library functions?
  • Is POSIX even implementable on a system where sizeof (function pointer) > sizeof (void *)?

References

  • The C11 Standard (final public draft): n1570
  • The POSIX Standard from The Open Group: POSIX.1-2008
  • The POSIX dlsym() function

回答1:


The dlsym() reference says the conversion is not defined by the C standard but that a conforming implementation has to make this work correctly. So on systems where this can not be made to work would not be a conforming implementation and would presumably document this:

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.

there is an old article that talks about this from the C++ perspective and links to an older version of the dlsym() reference and has a more detailed explanation:

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.



来源:https://stackoverflow.com/questions/27707048/posix-restrictions-on-pointer-types-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!