当需要指向全局函数的指针时,如何使用指针成员函数? [英] How to use pointer to member function when when pointer to global function is required?

查看:124
本文介绍了当需要指向全局函数的指针时,如何使用指针成员函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following problem. I have to use a function that takes a callback. Implementing the callback is the tricky part, because I need more information beyond that I can extract from the input parameters. I will try to give an example:

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

问题是我需要额外的信息,除了参数构造out参数。我尝试了这种方法:

The problem is that I need additional info except the "in" parameter to construct the "out" parameter. I tried this approach:

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

我从编译器得到以下错误:

I get the following error from the compiler:


错误:无法从类型'int(Wrapper ::)(char *,char *)'转换'Wrapper :: callback'类型'fptr {aka int(*)(char * ,char *)}'

error: cannot convert 'Wrapper::callback' from type 'int (Wrapper::)(char*, char*)' to type 'fptr {aka int(*)(char*, char*)}'


推荐答案

您需要传递需要传递的内容,这是一个指向函数的指针。

You need to pass what you need to pass, in this case a pointer to a function.

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

这篇关于当需要指向全局函数的指针时,如何使用指针成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆