Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/153.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 当需要指向全局函数的指针时,如何使用指向成员函数的指针?_C++_Pointers_Function Pointers - Fatal编程技术网

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

C++ 当需要指向全局函数的指针时,如何使用指向成员函数的指针?,c++,pointers,function-pointers,C++,Pointers,Function Pointers,我有以下问题。我必须使用一个接受回调的函数。实现回调是一个棘手的部分,因为除了可以从输入参数中提取的信息之外,我还需要更多的信息。我将尝试举一个例子: 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”参数之外的

我有以下问题。我必须使用一个接受回调的函数。实现回调是一个棘手的部分,因为除了可以从输入参数中提取的信息之外,我还需要更多的信息。我将尝试举一个例子:

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{aka int(*)(char*,char*)}”


您需要传递需要传递的内容,在本例中是指向函数的指针

::std::function<int (char*, char*)> forwardcall;

int mycallback(char* in, char* out) // extern "C"
{
  return forwardcall(in, out);
}

啊。如果没有希望更改您需要使用的接口来获取
std::function
或类似功能,那么
bind
或类似功能将无法帮助您。您只需创建一个包装器全局函数,它知道在哪里可以找到
wrapper
的一些实例,并在其上调用
callback
。这很糟糕,因为它有效地迫使您拥有某种全局数据。请参阅:即使您可以将指向成员的指针转换为普通函数指针(在可移植代码中不能),您如何期望
指针可用于回调?为什么
外部“C”
?错误中没有指示需要它。@BoBTFish只是为了以防万一。如果未声明
fptr
回调类型
extern“C”
,则在尝试将其传递给
takeFPtr
时,将其添加到回调中“以防万一”应该是一个错误(尽管大多数编译器没有实现该规则)@Jonathanly我不知道你能把
extern“C”
放入
typedef
中。有可能?[dcl.link]/1“具有不同语言链接的两种函数类型是不同的类型,即使它们在其他方面相同。”
forwardcall = [obj](char* in, char* out){ return obj->callback(in, out); };