Home  >  Article  >  Backend Development  >  How to Safely Cast a Void Pointer to a Function Pointer in C ?

How to Safely Cast a Void Pointer to a Function Pointer in C ?

Susan Sarandon
Susan SarandonOriginal
2024-11-05 00:43:02606browse

How to Safely Cast a Void Pointer to a Function Pointer in C  ?

Function Pointer Casting 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn