Function pointers casting in C++

前端 未结 8 1401
星月不相逢
星月不相逢 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:31

    I found this (a bit ugly) solution. gcc with maximum warning level does not complain. This example calls dlsym() (that returns a void*) and returns the result in a function pointer.

    typedef void (*FUNPTR)();
    
    FUNPTR fun_dlsym(void* handle, const char* name) {
        union {
            void* ptr;
            FUNPTR fptr;
        } u;
        u.ptr = dlsym(handle, name);
        return u.fptr;
    }
    

提交回复
热议问题