4

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*)}'

3
  • 3
    Ugh. If there's no hope of changing the interface you need to use to take a std::function or something, then bind or similar can't help you. You'll just have to create a wrapper global function that knows where to find some instance of Wrapper and call callback on it. This sucks because it effectively forces you to have some kind of global data. Commented Aug 1, 2014 at 10:08
  • 1
    see: stackoverflow.com/questions/1000663/… Commented Aug 1, 2014 at 10:09
  • Even if you could convert from a pointer to member to a normal function pointer (you can't in portable code*), how do you expect the this pointer to be available to the callback? Commented Aug 1, 2014 at 10:11

1 Answer 1

4

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); };
Sign up to request clarification or add additional context in comments.

8 Comments

Why extern "C"? There is no indication from the error it is needed.
@BoBTFish just in case it is needed.
if the fptr callback type isn't declared extern "C" then adding it to your callback "just in case" should be an error when you try to pass it to takeFPtr (although most compilers don't implement that rule)
@JonathanWakely I didn't know you could place extern "C" into a typedef. It is possible?
[dcl.link]/1 "Two function types with different language linkages are distinct types even if they are otherwise identical."
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.