Pittfall
Pittfall

Reputation: 2851

How can I call my set my callback function from an object?

Here is some code:

typedef void (*ACallBack)(int i);

class SomeClass
{
private:
   ACallBack aCallBack;

public:
   void SetCallBack(ACallBack aCallBack);
};

void SomeClass::SetCallBack(ACallBack aCallBack)
{
   this->aCallBack = aCallBack;
}

class SomeOtherClass
{
private:
   SomeClass someClass;

public:
   void InitializeSomeClass();

private:
   void callBackMethod(int i);
};

void SomeOtherClass::InitializeSomeClass()
{
   this->changeVariable = 10;

   this->someClass.SetCallBack(this->callBackMethod); // DOESN'T WORK
   this->someClass.UseCallBack();
}

void SomeOtherClass::callBackMethod(int i)
{
}

void globalCallBack(int i)
{
   int myInt = i;
}

int main()
{
   SomeClass sC;
   sC.SetCallBack(globalCallBack); //WORKS!!
}

Basically if I try to set my callback function in SomeOtherClass it doesn't work but when I set it globally in main it does. What am I missing here?

Upvotes: 0

Views: 203

Answers (2)

Slava
Slava

Reputation: 44268

Just use std::function and std::bind():

typedef std::function<void(int i)> ACallBack;

// old code pretty much the same

int main()
{
    using namespace std::placeholders;

    SomeClass sC;
    sC.SetCallBack(globalCallBack); //WORKS!!
    SomeOtherClass oC;
    sC.SetCallBack(std::bind(&SomeOtherClass::callBackMethod,oC,_1)); //WORKS AS WELL!!
}

In this case you do not really need to pass void *userData but may add it as well if you need old code to compile.

Upvotes: 1

Philip Stuyck
Philip Stuyck

Reputation: 7467

You have to make the method static:

static void callBackMethod(int i, void* userData);

if you need a pointer to a method that is not static, ie an instance method, it becomes more complex.

typedef void ( myclass::*FUNC ) (int i, void* userData);

and if you want to use it, it becomes a hastlle :

myclass obj;        // instantiate myclass
FUNC f = &myclass::myfunc;  // assign address
( obj.*f ) ( 123, NULL );   // and call it

Upvotes: 0

Related Questions