"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Can You Cast void Pointers to Function Pointers in C++?

Can You Cast void Pointers to Function Pointers in C++?

Published on 2024-11-08
Browse:413

Can You Cast void Pointers to Function Pointers in C  ?

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:

  • Reinterpret Cast:
fptr my_fptr = reinterpret_cast(reinterpret_cast(gptr));
  • Variable Reinterpretation:
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.

Latest tutorial More>

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