Home >Backend Development >C++ >How to Cast Between void* and a Pointer to Member Function in C ?
When working with C libraries, developers often encounter challenges in casting between void* and a pointer to member function. This article aims to address a specific issue related to this topic and provide a viable solution.
In an attempt to facilitate the binding of C objects to a Lua interpreter, a function, call_int_function, was designed using GCC 4.4. However, the line reinterpret_cast
GCC considers the cast from void to void (T::)(int, int) invalid because pointers-to-members are distinct from regular pointers. They are not addresses in the traditional sense, and their implementation varies significantly across compilers.
The solution to this issue lies in wrapping the member function within a regular function. The free function should take the object as its first argument. This approach eliminates the need to cast to void* and allows the use of a regular pointer to function type.
Here's a rewritten version of the call_int_function using the proposed solution:
<code class="cpp">template <class T> 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>
By wrapping the member function within a regular function, the need for casting to void* is eliminated, resolving the compilation error encountered in GCC 4.4. This approach maintains the intended functionality while adhering to the limitations and requirements of pointer-to-member casting.
The above is the detailed content of How to Cast Between void* and a Pointer to Member Function in C ?. For more information, please follow other related articles on the PHP Chinese website!