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:
<code class="cpp">fptr my_fptr = reinterpret_cast<fptr>(reinterpret_cast<long>(gptr));</code>
<code class="cpp">fptr my_ptr = 0; reinterpret_cast<void*&>(my_ptr) = gptr;</code>
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.
The above is the detailed content of Can You Cast void Pointers to Function Pointers in C ?. For more information, please follow other related articles on the PHP Chinese website!