Home > Article > Backend Development > How to Safely Cast a Void Pointer to a Function Pointer in C ?
Question:
You have a void pointer returned by dlsym(), and you need to call the function pointed to by this void pointer. You have tried casting with both static_cast and reinterpret_cast, but neither has worked. What options do you have?
Answer:
Directly converting a void pointer to a function pointer is disallowed in C 98/03. It may be conditionally supported in C 0x, but its behavior is implementation-defined.
Non-Standard Solutions:
Despite the standard's ambiguity, there are several non-standard solutions that may work on most platforms, although they are considered undefined behavior:
Option 1:
<code class="cpp">typedef void (*fptr)(); fptr my_fptr = reinterpret_cast<fptr>(reinterpret_cast<long>(gptr));</code>
Option 2:
<code class="cpp">fptr my_fptr = 0; reinterpret_cast<void*&>(my_fptr) = gptr;</code>
Option 3 (Slow Motion):
<code class="cpp">void (**object_ptr)() = &my_ptr; void **ppv = reinterpret_cast<void**>(object_ptr); *ppv = gptr;</code>
These options exploit the fact that the address of a function pointer is an object pointer, allowing for indirect casting using reinterpret_cast.
Note:
These solutions are not guaranteed to work on all platforms and are not considered standard C . Use them at your own risk.
The above is the detailed content of How to Safely Cast a Void Pointer to a Function Pointer in C ?. For more information, please follow other related articles on the PHP Chinese website!