当需要指向全局函数的指针时如何使用指向成员函数的指针

How to use pointer to member function when when pointer to global function is required?

本文关键字:指针 函数 何使用 成员 全局      更新时间:2023-10-16

我有以下问题。我必须使用一个接受回调的函数。实现回调是比较棘手的部分,因为我需要从输入参数中提取更多的信息。我来举个例子:

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