c++callbackfunction-pointersc++03

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


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 what I did from my constructor:

m_cRedundencyManager->Init(this->RedundencyManagerCallBack);

This doesn't compile - I get the following error:

Error 8 error C3867: 'CLoggersInfra::RedundencyManagerCallBack': function call missing argument list; use '&CLoggersInfra::RedundencyManagerCallBack' to create a pointer to member

I tried the suggestion to use &CLoggersInfra::RedundencyManagerCallBack - didn't work for me.

Any suggestions/explanation for this??

I'm using VS2008.

Thanks!!


Solution

  • 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<CLoggersInfra*>(this_pointer);
        self->RedundencyManagerCallBack(other_arg);
    }