How can I pass a class member function as a callback?

前端 未结 12 1919
忘掉有多难
忘掉有多难 2020-11-22 04:58

I\'m using an API that requires me to pass a function pointer as a callback. I\'m trying to use this API from my class but I\'m getting compilation errors.

Here is

12条回答
  •  时光取名叫无心
    2020-11-22 05:41

    Is m_cRedundencyManager able to use member functions? Most callbacks are set up to use regular functions or static member functions. Take a look at this page at C++ FAQ Lite for more information.

    Update: The function declaration you provided shows that m_cRedundencyManager is expecting a function of the form: void yourCallbackFunction(int, void *). Member functions are therefore unacceptable as callbacks in this case. A static member function may work, but if that is unacceptable in your case, the following code would also work. Note that it uses an evil cast from void *.

    
    // in your CLoggersInfra constructor:
    m_cRedundencyManager->Init(myRedundencyManagerCallBackHandler, this);
    
    
    // in your CLoggersInfra header:
    void myRedundencyManagerCallBackHandler(int i, void * CLoggersInfraPtr);
    
    
    // in your CLoggersInfra source file:
    void myRedundencyManagerCallBackHandler(int i, void * CLoggersInfraPtr)
    {
        ((CLoggersInfra *)CLoggersInfraPtr)->RedundencyManagerCallBack(i);
    }
    

提交回复
热议问题