对非静态C++成员函数的回调
Callback to a non-static C++ Member Function
我希望有人阐明这个让我感到困惑的代码片段。
//-------------------------------------------------------------------------------
// 3.5 Example B: Callback to member function using a global variable
// Task: The function 'DoItB' does something that implies a callback to
// the member function 'Display'. Therefore the wrapper-function
// 'Wrapper_To_Call_Display is used.
#include <iostream.h> // due to: cout
void* pt2Object; // global variable which points to an arbitrary object
class TClassB
{
public:
void Display(const char* text) { cout << text << endl; };
static void Wrapper_To_Call_Display(char* text);
/* more of TClassB */
};
// static wrapper-function to be able to callback the member function Display()
void TClassB::Wrapper_To_Call_Display(char* string)
{
// explicitly cast global variable <pt2Object> to a pointer to TClassB
// warning: <pt2Object> MUST point to an appropriate object!
TClassB* mySelf = (TClassB*) pt2Object;
// call member
mySelf->Display(string);
}
// function does something that implies a callback
// note: of course this function can also be a member function
void DoItB(void (*pt2Function)(char* text))
{
/* do something */
pt2Function("hi, i'm calling back using a global ;-)"); // make callback
}
// execute example code
void Callback_Using_Global()
{
// 1. instantiate object of TClassB
TClassB objB;
// 2. assign global variable which is used in the static wrapper function
// important: never forget to do this!!
pt2Object = (void*) &objB;
// 3. call 'DoItB' for <objB>
DoItB(TClassB::Wrapper_To_Call_Display);
}
问题 1:关于此函数调用:
DoItB(TClassB::Wrapper_To_Call_Display)
为什么Wrapper_To_Call_Display
不接受任何论据,尽管它应该根据其声明进行char*
论证?
问题 2:DoItB
声明为
void DoItB(void (*pt2Function)(char* text))
到目前为止,我所理解的是DoItB
将函数指针作为参数,但是为什么函数调用DoItB(TClassB::Wrapper_To_Call_Display)
将TClassB::Wrapper_To_Call_Display
作为参数甚至很难,它不是指针?
提前感谢
代码片段来源:http://www.newty.de/fpt/callback.html
在 C/C++ 中,当函数名称不带参数(即没有括号)使用时,它是指向函数的指针。 因此,TClassB::Wrapper_To_Call_Display
是指向内存中实现函数代码的地址的指针。
由于TClassB::Wrapper_To_Call_Display
是指向void
函数的指针,该函数采用单个char*
因此时间void (*)(char* test)
,因此它与DoItB
所需的类型相匹配。
相关文章:
- 以特征类型作为参数的泛型函数回调
- C# DllImport 调用非托管C++函数回调
- 为什么模板参数推导失败,std::函数回调的可变参数模板参数?
- std::包含 std::函数回调的多个包装器的向量不起作用
- 如何设置对类的私有函数的函数回调?
- 如何使用 c++11 函数回调声明多个模板参数
- sqlite3 更改函数回调参数 void* not用于 int* C++
- 如何知道 sqlite 中的函数"回调"是否返回了一些东西?
- Windows表单如何使用其他函数回调图表信息
- 如何在 c++ 结构中的 void* 变量中调用存储函数(回调)
- 将成员函数作为标准函数回调
- C++ 使用成员函数回调实现按钮
- std::函数回调,参数采用观察者模式(寄存器主题上的占位符)
- 使用可变参数模板从 Lua 函数回调 (C api) 中提取参数
- 在C++中使用派生类的静态方法作为函数回调
- 将libuv与函数结构一起使用,而不是函数回调
- 如何将函数回调传递给类成员
- c++类成员函数回调
- C++函数回调:无法从成员函数转换为函数签名
- 如何编写一个通用函数回调测试类