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:
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>
2. Use a Function Object:
Other Considerations:
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!