如何将类成员函数作为回调传递

如何将类成员函数作为回调传递

本文介绍了如何将类成员函数作为回调传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的 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"创建一个指向成员的指针

我尝试了使用 &CLoggersInfra::RedundencyManagerCallBack 的建议 - 对我不起作用.

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

对此有何建议/解释??

Any suggestions/explanation for this??

我使用的是 VS2008.

I'm using VS2008.

谢谢!!

推荐答案

这不起作用,因为成员函数指针不能像普通函数指针一样处理,因为它需要一个this"对象参数.

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);

函数可以定义如下

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

这篇关于如何将类成员函数作为回调传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 06:44