C++ class member function pointer to function pointer

后端 未结 4 1744
情话喂你
情话喂你 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 20:13

    Not suitable for your LUA problem, but maybe on other libraries: If a function requests a a function pointer like func(void* param, ...) and you can ensure that the lifetime of your object is greater than the stored function pointer, then you could technically also use a method pointer (looks the same on the stack), but C++ prevents direct casting of method pointers to function pointers.

    But with a little trick, you can also cast method pointers to function pointers:

    template inline void* GetMethodPointer(M ptr)
    {
        return *reinterpret_cast(&ptr);
    }
    

    Using that, you can use method pointers for example with libmicrohttpd:

    this->m_pDaemon = MHD_start_daemon(MHD_USE_THREAD_PER_CONNECTION, this->m_wPort, NULL, NULL, reinterpret_cast(GetMethodPointer(&CMyWebServer::AccessHandlerCallback)), this, MHD_OPTION_END);
    

    But be aware of it. You must take care of the lifetime of that object. Also the calling conventions must match.

提交回复
热议问题