Home > Backend Development > C++ > body text

Can You Cast void Pointers to Function Pointers in C ?

Barbara Streisand
Release: 2024-11-02 21:20:30
Original
385 people have browsed it

Can You Cast void Pointers to Function Pointers in C  ?

Casting Void Pointers to Function Pointers in C

Converting void pointers returned by functions like dlsym() to function pointers is not straightforward in C . By default, such direct casting is prohibited in C 98/03.

Reason for Restriction

In C 98/03, void* pointers were intended for referencing objects, not function or member pointers.

Conditional Support in C 0x

In C 0x, casting void* to function pointers is optionally supported by implementations. If supported, the behavior must conform to the standard.

Implementation-Dependent Workarounds

While direct casting is not allowed, these workarounds may function on most platforms:

  • Reinterpret Cast:
<code class="cpp">fptr my_fptr = reinterpret_cast<fptr>(reinterpret_cast<long>(gptr));</code>
Copy after login
  • Variable Reinterpretation:
<code class="cpp">fptr my_ptr = 0;
reinterpret_cast<void*&>(my_ptr) = gptr;</code>
Copy after login

These workarounds exploit the fact that function pointer addresses are objects and can be converted to void** pointers using reinterpret_cast.

Cautionary Note

These workarounds involve undefined behavior and should be used with discretion.

The above is the detailed content of Can You Cast void Pointers to Function Pointers 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!