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

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

    That doesn't work because a member function pointer cannot be handled like a normal function pointer, because it expects a "this" object argument.

    Instead you can pass a static member function as follows, which are like normal non-member functions in this regard:

    m_cRedundencyManager->Init(&CLoggersInfra::Callback, this);
    

    The function can be defined as follows

    static void Callback(int other_arg, void * this_pointer) {
        CLoggersInfra * self = static_cast(this_pointer);
        self->RedundencyManagerCallBack(other_arg);
    }
    

提交回复
热议问题