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
Release: 2024-11-03 01:36:02
Original
600 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template