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

∥☆過路亽.° 提交于 2019-12-10 16:46:27

问题


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

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:

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


回答1:


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 can contain any functor, for example:

forwardcall = [obj](char* in, char* out){ return obj->callback(in, out); };


来源:https://stackoverflow.com/questions/25077611/how-to-use-pointer-to-member-function-when-when-pointer-to-global-function-is-re

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!