Page 1 of 1

Bind velocity_func to member method

Posted: Wed Feb 08, 2012 12:14 pm
by con
I've recently started using chipmunks and I really like it.
Except for one problem with OOP: Because chipmunk is written in plain C, I'm not able to bind the velocity_func to a non-static member method (C++). I've tried several workarounds so far but hadn't any luck with this.
I understand that pointer to member methods are a different size, then pointer to functions. Had anyone the same problem and found a Solution? Some code:

Code: Select all

class Player{
public:
    Player();
    ~Player();
    void playerUpdateVelocity(cpBody *body, cpVect gravity, cpFloat damping, cpFloat dt);
protected:
private:
    cpBody *playerBody;
};

Player::Player(){
    playerBody = cpBodyNew(1.0f, INFINITY);
    playerBody->velocity_func = playerUpdateVelocity;
}

void Player::playerUpdateVelocity(cpBody *body, cpVect gravity, cpFloat damping, cpFloat dt){
// do something
}
That works only, as if the playerUpdateVelocity method is static (4th line, add "static" to the method declaration). What I want to accomplish: bind it to an member function, so that I can creat multiple "Players". Is this even possbile? Or did I made a fatal code design misstake?

Thanks for any help!

Re: Bind velocity_func to member method

Posted: Wed Feb 08, 2012 12:59 pm
by slembcke
Sure, you just have to wrap it with a function. Something like this:

Code: Select all

cpBody *someBodyToLove = cpBodyNew(...);
someBodyToLove->data = myCPPObject;
someBodyToLove->velocity_func = CallVelocityFunc;

CallVelocityFunc(cpBody *body, cpVect gravity, cpFloat damping, cpFloat dt)
{
  ((MyCPPClass *)body->data)->VelocityUpdateMethod();
}
Pretty much the same thing you need to do when wrapping the API for any other language. Nearly every language in existence can use C functions, it's just a question of getting the data you need into them. That's why most callbacks in Chipmunk also take a user defined "data" parameter. In the case of callbacks on bodies, shape, constraints, etc, you have the data pointer on the object that you can use to point back to your "real" object.

Re: Bind velocity_func to member method

Posted: Wed Feb 08, 2012 1:32 pm
by con
Great, thank you!
Works like a charm!