C++ class member function pointer to function pointer

后端 未结 4 1738
情话喂你
情话喂你 2020-12-06 19:32

I am using luabind as my lua to C++ wrapper. Luabind offers a method to use my own callback function to handle exceptions thrown by lua, set_pcall_callback(). So I paraphras

4条回答
  •  独厮守ぢ
    2020-12-06 19:58

    Explicit conversion from method pointer to function pointer is illegal in C++ - period.

    But there is a hack. We have to first convert the (const) method pointer to (const) void* and then to (const) function pointer. And it works. And why wouldn't it? Everything and I mean everything can be pointed to by a void* because everything has an address.


    WARNING: The below is DAAEINGEROUS hack territory. If you're developing software for a fighter jet or whatnot, you should know better than to use this. I'm not responsible! I'm just providing this here for educational purposes.


    The trick is that you can't call a member function pointer through a void* object in memory. The pointer must be converted to a pointer of the target object's class type. However you can call the same member function through a function pointer to void* to this* object.

    Given a: MethodPointerType f;

    then

    FunctionPointerType m_pFn = reinterpret_cast( reinterpret_cast( f ) );
    

    or to make it more explicit use two of the following in sequence, for non-const and const member functions:

    template
    void* getMethodVoidPointer( MP ptr )
    {
        return *reinterpret_cast( &ptr );
    }
    template
    FP getFunctionPointer( void* p )
    {
        return reinterpret_cast( p );
    }
    template
    const void* getMethodConstVoidPointer( MP ptr )
    {
        return *reinterpret_cast( &ptr );
    }
    template
    FP getConstFunctionPointer( const void* p )
    {
        return reinterpret_cast( p );
    }
    

    Play with it live here with a complete compilable sample in C++17: https://onlinegdb.com/HybR8crqw

    It works in Visual Studio too.

提交回复
热议问题