问题
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