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

前端 未结 12 1926
忘掉有多难
忘掉有多难 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:34

    The type of pointer to non-static member function is different from pointer to ordinary function.
    Type is void(*)(int) if it’s an ordinary or static member function.
    Type is void(CLoggersInfra::*)(int) if it’s a non-static member function.
    So you cannot pass a pointer to a non-static member function if it is expecting an ordinary function pointer.

    Furthermore, a non-static member function has an implicit/hidden parameter to the object. The this pointer is implicitly passed as an argument to the member function call. So the member functions can be invoked only by providing an object.

    If the API Init cannot be changed, a wrapper function (ordinary function or a class static member function) that invokes the member can be used. In the worst case, the object would be a global for the wrapper function to access.

    CLoggersInfra* pLoggerInfra;
    
    RedundencyManagerCallBackWrapper(int val)
    {
        pLoggerInfra->RedundencyManagerCallBack(val);
    }
    
    m_cRedundencyManager->Init(RedundencyManagerCallBackWrapper);
    

    If the API Init can be changed, there are many alternatives - Object non-static member function pointer, Function Object, std::function or Interface Function.

    See the post on callbacks for the different variations with C++ working examples.

提交回复
热议问题