Sign in to follow this  

Passing a C++ member function as a C callback function

This topic is 3601 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm making use of the callback functions in GLFW. The functions that set these take as a parameter the pointer to an appropriate function. Unfortunately, they can only take a global/static function, not the member function of an object instance like I want. I've managed to get it working in a somewhat hackish way:
void Callback();

class MyObject
{
  public:
    static MyObject* instance;

    MyObject()
    {
        instance = this;
        C_Api_Set_Callback( Callback );
    }

    void FunctionToCall()
    {
      // Does something amazing here
    }
}

void Callback()
{
  MyObject::instance->FunctionToCall();
}
This works, but I'm wondering if somebody knows of a more elegant solution. For this particular class, at the current time, I only need one instance. But if I ever wanted more than one, instance will only point to the newest. Of course, the C library can't have multiple callback functions anyway... but nevertheless, any general advice from people who've dealt with this situation?

Share this post


Link to post
Share on other sites
If you can't pass a single pointer-sized value to callback as a token, then there is no other way.

If you can, then you pass this pointer to the function along with static function to callback.

The static callback then looks something like this:

static void global_callback( int p1, int p2, void * token)
{
static_cast<MyObject*>(token)->real_callback(p1, p2);
}

...

// pass relevant parameters
invoke( this, &global_callback);

// where invoke is
static void invoke( void * token, void (*f)(int, int) );

Share this post


Link to post
Share on other sites

This topic is 3601 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this