Home > C++, Software Development > C++ Callbacks

C++ Callbacks

C – style callbacks are straight forward to declare and implement. C++ callbacks are less trivial due to the nature of the thiscall convention. Calls adhering to this convention transparently pass a pointer of the current instance to the function/method.
How the instance pointer is passed is compiler specific. GCC pushes it on the stack as a last parameter, MSVC will pass it in ECX except when calling vararg functions.
It is still possible to execute callbacks if they are stored in the same class, but when stored in an external location it is not possible to invoke a thiscall callback directly. Here is a small workaround:

typedef struct SomeStorage
{
    // ...
    VOID (MyClass::*MyMethodPtr)(); 
};
class Myclass
{
public:
    void SomeMethod()
    {
        SomeStorage ss;
        ss.MyMethodPtr = &MyClass::MyMethod;
        this->MyMethodPtr= ss.MyMethodPtr;
        (this->*MyMethodPtr)( void );
    }
private:
    void (MyClass::*MyMethodPtr)( void ); // dummy
    void MyMethod()
    {
        // ...
    }
};

The trick is to temporarily store the retrieved pointer in a member variable and dereference it from there using the ->* operator.

See:

  1. No comments yet.
  1. No trackbacks yet.