Jump to content
  • Advertisement
Sign in to follow this  
Gamer Gamester

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

This topic is 3786 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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!