我如何传递一个类成员函数作为回调?

我如何传递一个类成员函数作为回调?

问题描述:

我使用的API要求我传递一个函数指针作为回调。我试图从我的类使用这个API,但我收到编译错误。

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:


错误8错误C3867:'CLoggersInfra :: RedundencyManagerCallBack':函数调用缺少参数列表;使用'& CLoggersInfra :: RedundencyManagerCallBack'创建指向成员的指针

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

我试过建议使用 & CLoggersInfra :: RedundencyManagerCallBack - 没有为我工作。

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

此建议/解释?

我使用VS2008。

谢谢!

由于你现在显示你的init函数接受一个非成员函数。所以做这样:

As you now showed your init function accepts a non-member function. so do it like this:

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

并调用Init与

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

这样做是因为指向静态成员函数的函数指针不是成员函数指针,处理就像只是一个*功能的指针。

That works because a function pointer to a static member function is not a member function pointer and can thus be handled like just a pointer to a free function.