"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Can C++ Convert a Void Pointer to a Function Pointer?

Can C++ Convert a Void Pointer to a Function Pointer?

Published on 2024-11-12
Browse:183

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:

void *gptr = dlsym(some symbol..);
typedef void (*fptr)();
fptr my_fptr = reinterpret_cast(reinterpret_cast(gptr));

Alternatively:

fptr my_ptr = 0;
reinterpret_cast(my_ptr) = gptr;

Complex but Portable Approach:

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

// Get address as object pointer
void (**object_ptr)() = &my_ptr;

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

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

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

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3