Is there such a thing as a generic function pointer in C that can be assigned/casted to a more restrictive prototype?

后端 未结 3 1484
名媛妹妹
名媛妹妹 2021-01-04 04:40

I have the need to dynamically link against a library at run-time and resolve a series of functions using dlsym. My first thought was to use an array of functio

3条回答
  •  不知归路
    2021-01-04 05:11

    dlsym returns a data pointer of type void *, but POSIX guarantees that this can be cast to a function pointer of the appropriate type:

    Implementations supporting the XSI extension [...] 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.

    Since Version 7 of POSIX, all implementations (not just XSI) are required to support the conversion.

    Because conversion from a void * pointer to a function pointer via a direct cast can result in compiler warnings, older versions of POSIX recommend performing the conversion via aliasing:

    int (*fptr)(int);
    *(void **)(&fptr) = dlsym(handle, "my_function");
    

    In the current version the recommendation is changed to:

    int (*fptr)(int);
    fptr = (int (*)(int))dlsym(handle, "my_function");
    

提交回复
热议问题