Home > Backend Development > C++ > body text

How to Cast Between a void* Pointer and a Pointer to a Member Function in C ?

Patricia Arquette
Release: 2024-10-27 20:48:30
Original
193 people have browsed it

How to Cast Between a void* Pointer and a Pointer to a Member Function in C  ?

Casting between void* and a Pointer to Member Function

When working with C/C interoperability, one can encounter difficulties when attempting to cast between a void pointer and a pointer to a member function. This issue often arises when dealing with closures in languages like Lua, where user data is stored as void pointers.

Problem:

Casting void* to a pointer to a member function in C is invalid due to the fundamental differences in their memory representations. Pointers-to-members contain additional information not accessible through regular pointers.

Solution:

To workaround this, consider the following options:

1. Wrap the Member Function in a Free Function:

  • Create a free function that accepts the object instance as its first argument and the member function parameters as subsequent arguments.
  • Return the address of this free function instead of the pointer-to-member.

Code Snippet:

<code class="cpp">int call_int_function(lua_State *L) {
    void (*method)(T*, int, int) = reinterpret_cast<void (*)(T*, int, int)>(lua_touserdata(L, lua_upvalueindex(1)));
    T *obj = reinterpret_cast<T *>(lua_touserdata(L, 1));

    method(obj, lua_tointeger(L, 2), lua_tointeger(L, 3));
    return 0;
}</code>
Copy after login

2. Use a Function Object:

  • Utilize a technique similar to Boost.Bind's mem_fun to create a function object that wraps the member function.
  • Template the function object to support different object types.

Other Considerations:

  • Ensure control over the user data returned by lua_touserdata as it cannot contain a valid pointer-to-member.
  • Consider wrapping the member function in a class method or static function if you require additional state.

The above is the detailed content of How to Cast Between a void* Pointer and a Pointer to a Member Function 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!