Function pointers casting in C++

前端 未结 8 1406
星月不相逢
星月不相逢 2020-11-27 15:45

I have a void pointer returned by dlsym(), I want to call the function pointed by the void pointer. So I do a type conversion by casting:

void *gptr = dlsym(         


        
8条回答
  •  庸人自扰
    2020-11-27 16:13

    You can cast dlsym to a function that returns the required pointer and then call it like this:

    typedef void (*fptr)();
    fptr my_fptr = reinterpret_cast(dlsym)(RTLD_DEFAULT, name);
    

    PS. Casting a function pointer to a different function pointer and then calling it is undefined behavior (see point 7 in https://en.cppreference.com/w/cpp/language/reinterpret_cast) so it is better to cast the result of dlsym to uintptr_t and then to the required type:

    fptr my_fptr = reinterpret_cast(reinterpret_cast(dlsym(RTLD_DEFAULT, name)));
    

提交回复
热议问题