How to setup a callback?

If you are a new Irrlicht Engine user, and have a newbie-question, this is the forum for you. You may also post general programming questions here.
Post Reply
Slywater
Posts: 7
Joined: Fri May 25, 2018 8:09 am

How to setup a callback?

Post 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.
MartinVee
Posts: 139
Joined: Tue Aug 02, 2016 3:38 pm
Location: Québec, Canada

Re: How to setup a callback?

Post 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.
Last edited by MartinVee on Fri Jun 01, 2018 7:55 pm, edited 1 time in total.
CuteAlien
Admin
Posts: 9670
Joined: Mon Mar 06, 2006 2:25 pm
Location: Tübingen, Germany
Contact:

Re: How to setup a callback?

Post 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.
IRC: #irrlicht on irc.libera.chat
Code snippet repository: https://github.com/mzeilfelder/irr-playground-micha
Free racer made with Irrlicht: http://www.irrgheist.com/hcraftsource.htm
Slywater
Posts: 7
Joined: Fri May 25, 2018 8:09 am

Re: How to setup a callback?

Post by Slywater »

Thanks both of you, it's now working as intended.
Post Reply