POSIX restrictions on pointer types in C

2020-03-10 05:02发布

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

1条回答
▲ chillily
2楼-- · 2020-03-10 05:32

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.

查看更多
登录 后发表回答