Function Pointer Casting in C
In C , converting a void* to a function pointer directly is generally not allowed. However, there are a few approaches that may work depending on the implementation and platform.
Method 1 (Undefined Behavior):
This method involves double reinterpret_casting:
<code class="cpp">void *gptr = dlsym(some symbol..); typedef void (*fptr)(); fptr my_fptr = reinterpret_cast<fptr>(reinterpret_cast<long>(gptr));</code>
Method 2 (Avoids Direct Conversion):
This method uses an intermediate step to store the function pointer address in a variable:
<code class="cpp">fptr my_ptr = 0; reinterpret_cast<void*&>(my_ptr) = gptr;</code>
Slower but More Transparent Version of Method 2:
<code class="cpp">void (**object_ptr)() = &my_ptr; void ** ppv = reinterpret_cast<void**>(object_ptr); *ppv = gptr;</code>
Limitations and Caveats:
Note:
In C 0x, the behavior of converting a void* to a function pointer is conditionally supported.
The above is the detailed content of How Can I Safely Cast a `void*` to a Function Pointer in C ?. For more information, please follow other related articles on the PHP Chinese website!