C++ class member function pointer to function pointer

后端 未结 4 1748
情话喂你
情话喂你 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:23

    No. A member function is not a free function. The type is entirely different, and a pointer to a member function (PTMF) is a completely different, incompatible object from a function pointer. (A PTMF is usually much bigger, for example.) Most importantly a pointer-to-member must always be used together with an instance pointer to the object whose member you want to call, so you cannot even use a PTMF the same way you use a function pointer.

    The easiest solution for interacting with C code is to write a global wrapper function that dispatches your call, or to make your member function static (in which case it becomes essentially a free function):

    // global!
    
    Engine * myEngine;
    int theCallback(lua_State * L)
    {
      return myEngine->pcall_log(L);
    }
    
    Engine::Run()
    {
      /* ... */
      myEngine = this;
      luabind::set_pcall_callback(&theCallback);
      /* ... */
    }
    

    The conceptual problem here is that you have an engine class, although you will practically only have one single instance of it. For a genuine class with many objects, a PTMF wouldn't make sense because you'd have to specify which object to use for the call, whereas your engine class perhaps is essentially a singleton class which could be entirely static (i.e. a glorified namespace).

提交回复
热议问题