Home >Backend Development >C++ >How Can I Safely Cast a `void*` to a Function Pointer in C ?

How Can I Safely Cast a `void*` to a Function Pointer in C ?

DDD
DDDOriginal
2024-11-03 01:36:02633browse

How Can I Safely Cast a `void*` to a Function Pointer in C  ?

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:

  • These methods are implementation-dependent and their behavior is not guaranteed by the C standard.
  • They may cause undefined behavior on some platforms or with certain compilers.
  • It's recommended to always check the validity of the pointer before using it as a function pointer.

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!

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