当需要指向全局函数的指针时如何使用指向成员函数的指针
How to use pointer to member function when when pointer to global function is required?
我有以下问题。我必须使用一个接受回调的函数。实现回调是比较棘手的部分,因为我需要从输入参数中提取更多的信息。我来举个例子:
typedef int (*fptr) (char* in, char* out); // the callback i have to implement
int takeFptr(fptr f, char* someOtherParameters); // the method i have to use
问题是,除了"in"参数之外,我还需要其他信息来构造"out"参数。我尝试了这个方法:
class Wrapper {
public:
int callback(char* in, char* out){
// use the "additionalInfo" to construct "out"
}
char* additionalInfo;
}
...
Wrapper* obj = new Wrapper();
obj->additionalInfo = "whatIneed";
takeFptr(obj->callback, someMoreParams);
我从编译器得到以下错误:
错误:无法将'Wrapper::callback'从类型'int (Wrapper::)(char*, char*)'转换为类型'fptr{也称为int(*)(char*, char*)}'
您需要传递您需要传递的内容,在本例中是指向函数的指针。
::std::function<int (char*, char*)> forwardcall;
int mycallback(char* in, char* out) // extern "C"
{
return forwardcall(in, out);
}
forwardcall
可以包含任意函子,例如:
forwardcall = [obj](char* in, char* out){ return obj->callback(in, out); };
相关文章:
- 如何正确编写指针函数声明?
- C++常规指针函数或模板
- 如何重新定义 C++ 指针函数?
- C++ 指向其他类函数的指针函数
- 指针到指针函数参数
- 将指向成员的指针函数传递到模板中
- C++ 在 none 常量指针函数中返回一个常量指针
- 如何使用指针函数编写/读取数组
- 是C 中的函数指针函数对象
- 如何从另一个类调用指向成员的指针函数
- 如何声明采用指向成员的指针函数的函数
- 如何构造一个以可变参数指针函数作为成员的类?
- c 通过值或指针函数语法
- 将typedef方法作为指针函数传递
- 从 Main 中的双指针函数打印出指针数组
- strcpy 对指针函数的引用
- 这是否仍然声明一种指针函数的别名?
- 将指向成员的指针函数与 std::shared_ptr 结合使用
- 'Incomplete type' 为标准::函数声明指向成员的指针函数模板参数时出错
- 从注入进程的 DLL 调用函数并更改指针函数的地址