Casting Void Pointers to Function Pointers in C
Converting void pointers returned by functions like dlsym() to function pointers is not straightforward in C . By default, such direct casting is prohibited in C 98/03.
Reason for Restriction
In C 98/03, void* pointers were intended for referencing objects, not function or member pointers.
Conditional Support in C 0x
In C 0x, casting void* to function pointers is optionally supported by implementations. If supported, the behavior must conform to the standard.
Implementation-Dependent Workarounds
While direct casting is not allowed, these workarounds may function on most platforms:
fptr my_fptr = reinterpret_cast(reinterpret_cast(gptr));
fptr my_ptr = 0;
reinterpret_cast(my_ptr) = gptr;
These workarounds exploit the fact that function pointer addresses are objects and can be converted to void** pointers using reinterpret_cast.
Cautionary Note
These workarounds involve undefined behavior and should be used with discretion.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3