Software development Tips and Tricks
From Emma
Important info about exposing functions to Lua
Today, we expose functions to Lua like this:
registerFunction("get_translation", TransformNode::get_translation);
But I found out an important thing today. The above causes a crash because get_translation is a virtual function, declared in ITransform and implemented by TransformNode. But, because ITransform is not the first derivation of TransformNode, the function pointer gets all confused and runs off into the weeds.
The reason is simple. Since this is a virtual function, it goes through the vtable. But since it is not defined origninally in the first derived class, it is not in the first vtable! So, when we thunk this and look in the first vtable... BOOM!
The solution is simple. The generated thunks already need to dynamic_cast the object so it can find the function pointer in the first place. But it uses the "TransformNode::" part of the function declaration as the target type of the cast. So you simply need to do this:
registerFunction("get_translation", ITransform::get_translation);
and everything works because it casts the object to the vtable of ITransform and then makes the call, using the correct vtable and the cortrect function pointer.
Unfortunately the VC++ compiler does not catch this, so it is easy to make the mistake. Just make sure to always use the highest derived class version of the function pointer and all should be well...
