Callback to member function with arguments

Is it possible to make a callback to a member function with arguments. Is there any preferred “workaround” if not possible?

For example (just for illustration, not necessarily complete nor compilable):


void function1(int *somearg) {
    // do something with somearg
};

class Example {
private:
    Thread *_pExampleThread;

    void function2() {
        // do something with.... uhh... nothing?
    };

    void function_wanted(int *somearg) {
        // do something with somearg
    };

public:
    void setup1(int exposed_arg) {
        // this works, but calls static func
        _pExampleThread->start(callback(function1, &exposed_arg));
    };

    void setup2(int exposed_arg) {
        // this also works, but takes no args
        _pExampleThread->start(callback(this, &Example::function2));
    };

    void setup_wanted(int exposed_arg) {
      // how to make something like this work?
        _pExampleThread->start(callback(this, &Example::function_wanted, &exposed_arg));
    };
}

I think I can’t use global vars or similar workaround since there’s possibility the (member) function is called multiple times.

Hello Ardian,

Is it possible to make a callback to a member function with arguments?

If the member function is static it is possible to pass one argument to the callback function in Thread’s start method.
For example:

class Example {
private:
    Thread *_pExampleThread;

    static void function_wanted(int *somearg) {
        // do something with somearg
    }

public:
    void setup_wanted(int exposed_arg) {
      // how to make something like this work?
        _pExampleThread->start(callback(&Example::function_wanted, &exposed_arg));
    }
};

Best regards, Zoltan

Wouldn’t static members not have access to object’s other members/variables? Which is yet another problem.

Static methods can access only static data members and call static methods. But that isn’t a Mbed problem. That’s a C++ design rule.

I mean it’s Mbed (current) callback limitation that it can’t pass a member function and argument at the same time.

Yes, Thread's start method is designed that way but there are other cases when callback to member functions allow to pass arguments.

I ended up “wrapping” the callback using EventQueue that does accept member function with args.

Can you please share how implemented such a solution? I’m kind of a beginner and am facing a similar situation