对非静态C++成员函数的回调

Callback to a non-static C++ Member Function

本文关键字:函数 回调 成员 C++ 静态      更新时间:2023-10-16

我希望有人阐明这个让我感到困惑的代码片段。

   //-------------------------------------------------------------------------------
   // 3.5 Example B: Callback to member function using a global variable
   // Task: The function 'DoItB' does something that implies a callback to
   //       the member function 'Display'. Therefore the wrapper-function
   //       'Wrapper_To_Call_Display is used.
   #include <iostream.h>   // due to:   cout
   void* pt2Object;        // global variable which points to an arbitrary object
   class TClassB
   {
   public:
      void Display(const char* text) { cout << text << endl; };
      static void Wrapper_To_Call_Display(char* text);
      /* more of TClassB */
   };

   // static wrapper-function to be able to callback the member function Display()
   void TClassB::Wrapper_To_Call_Display(char* string)
   {
       // explicitly cast global variable <pt2Object> to a pointer to TClassB
       // warning: <pt2Object> MUST point to an appropriate object!
       TClassB* mySelf = (TClassB*) pt2Object;
       // call member
       mySelf->Display(string);
   }

   // function does something that implies a callback
   // note: of course this function can also be a member function
   void DoItB(void (*pt2Function)(char* text))
   {
      /* do something */
      pt2Function("hi, i'm calling back using a global ;-)");   // make callback
   }

   // execute example code
   void Callback_Using_Global()
   {
      // 1. instantiate object of TClassB
      TClassB objB;

      // 2. assign global variable which is used in the static wrapper function
      // important: never forget to do this!!
      pt2Object = (void*) &objB;

      // 3. call 'DoItB' for <objB>
      DoItB(TClassB::Wrapper_To_Call_Display);
   }

问题 1:关于此函数调用:

DoItB(TClassB::Wrapper_To_Call_Display)

为什么Wrapper_To_Call_Display不接受任何论据,尽管它应该根据其声明进行char*论证?

问题 2:DoItB声明为

void DoItB(void (*pt2Function)(char* text))

到目前为止,我所理解的是DoItB将函数指针作为参数,但是为什么函数调用DoItB(TClassB::Wrapper_To_Call_Display)TClassB::Wrapper_To_Call_Display作为参数甚至很难,它不是指针?

提前感谢

代码片段来源:http://www.newty.de/fpt/callback.html

在 C/C++ 中,当函数名称不带参数(即没有括号)使用时,它是指向函数的指针。 因此,TClassB::Wrapper_To_Call_Display是指向内存中实现函数代码的地址的指针。

由于TClassB::Wrapper_To_Call_Display是指向void函数的指针,该函数采用单个char*因此时间void (*)(char* test),因此它与DoItB所需的类型相匹配。