Page 1 of 1

How to setup a callback?

Posted: Fri Jun 01, 2018 3:14 pm
by Slywater
Hi, sorry for another post.
I tried to setup an end of animation callback for one of my models, but the application crashes with the following code:

Code: Select all

IAnimationEndCallBack* walkCall;
walkCall->OnAnimationEnd(light);
light->setAnimationEndCallback(walkCall);
light->setLoopMode(false);
I'm sure I'm doing something wrong, but I'm not sure what. If anybody could tell me why it breaks, that would be great.

Re: How to setup a callback?

Posted: Fri Jun 01, 2018 3:46 pm
by MartinVee
You need to implement and instance a class derived from IAnimationEndCallBack.

Here's a quick and dirty example :

Code: Select all

 
class AnimEndCallback : public IAnimationEndCallBack
{
  public:
    void OnAnimationEnd( IAnimatedMeshSceneNode *node)
    {
      printf("The animation has ended!\r\n");
      // Your callback code goes there.
    }
};
 
[...snip...]
 
AnimEndCallback *animEndCallBack = new AnimEndCallback();
walkCall->OnAnimationEnd(light);
light->setAnimationEndCallback(animEndCallBack);
light->setLoopMode(false);
animEndCallBack->drop();
 
 
In case you're wondering, the problem is that you're declaring an uninitialized pointer to a virtual class, and you pass that uninitialized pointer to be called back later. Best case scenario, your pointer is initialized to NULL and nothing will happen. Worst case scenario, the random value assigned to walkCall actually maps to accessible memory, and the code summons Cthulhu.

UPDATE : Updated the derived class creation method to use new as CuteAlien suggested.

Re: How to setup a callback?

Posted: Fri Jun 01, 2018 6:28 pm
by CuteAlien
Don't create the object on the stack - IAnimationEndCallback is derived from IReferenceCounted.
So like MartinVee mentioned - needs instances of some own class derived from IAnimationEndCallback.
But make sure the instance is allocated with new.

Re: How to setup a callback?

Posted: Sat Jun 02, 2018 11:30 am
by Slywater
Thanks both of you, it's now working as intended.