Home  >  Article  >  Backend Development  >  Can C Convert a Void Pointer to a Function Pointer?

Can C Convert a Void Pointer to a Function Pointer?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-03 04:42:31756browse

Can C   Convert a Void Pointer to a Function Pointer?

Converting Void Pointers to Function Pointers: A Conditional Possibility in C

Problem

Obtaining a void pointer via dlsym(), the goal is to invoke the function referenced by that pointer. The attempted conversion through casting using static_cast or reinterpret_cast has failed, unlike a C-style cast.

Answer

Direct conversion of a void pointer to a function pointer is impermissible in C 98/03. However, C 0x offers conditional support, allowing an implementation to dictate the behavior.

Undefined Behavior Approach:

While undefined by the standard, the following code may work on most platforms:

<code class="cpp">void *gptr = dlsym(some symbol..);
typedef void (*fptr)();
fptr my_fptr = reinterpret_cast<fptr>(reinterpret_cast<long>(gptr));</code>

Alternatively:

<code class="cpp">fptr my_ptr = 0;
reinterpret_cast<void*&>(my_ptr) = gptr;</code>

Complex but Portable Approach:

This method exploits the fact that a function pointer's address is an object pointer:

<code class="cpp">// Get address as object pointer
void (**object_ptr)() = &my_ptr;

// Convert to void** (also an object pointer)
void **ppv = reinterpret_cast<void**>(object_ptr);

// Store address from 'gptr' in memory cell pointed to by 'ppv'
*ppv = gptr;</code>

This approach remains undefined in the standard but should function reasonably well on most implementations.

The above is the detailed content of Can C Convert a Void Pointer to a Function Pointer?. 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