C++/SDL 'void*' is not a point-to-object type
I'm new on C++ and I'm trying to make some testing with C++ and SDL and in SDL we have a function:
SDL_TimerID SDL_AddTimer(Uint32 interval, SDL_NewTimerCallback callback, void *param);
which I can pass a callback for the timer created. But apparently it converts my instance this to *void so I can't retrieve it again on the update method which is static, and it's interesting but the the SDL_AddTime doesn't work on a non static callback function.
Well, so my problem is that when trying to call the public method render through the void* param argument It complains about not being a pointer-to-object-type...
Is there any way I can get the Character instance again inside the update method since I don't have control over the SDL_AddTime function and I have to pass the required parameters?
Thanks
#include "Character.h"
Character::Character(void)
{
timer = SDL_AddTimer(33, update, this);
this->render(); // is called without problem
}
//static method
Uint32 Character::update(Uint32 interval,void* param)
{
param->render(); // yields: 'void*' is not a pointer-to-object type;
SDL_Event event;
event.t开发者_开发问答ype = SDL_USEREVENT;
event.user.code = 1020;
event.user.data1 = param;
SDL_PushEvent(&event);
return interval;
}
void Character::render(void)
{
printf("rendering character \n");
}
You don't need a reinterpret_cast - a static_cast should be OK:
Character * cp = static_cast <Character *>( param );
You should avoid reinterpret_cast - it is almost always implementation specific, and may hide problems - just like old-style C casts.
Cast your param pointer to a Character:
Character * charPtr = reinterpret_cast<Character *>(param);
charPtr->render();
The reason is that C++ is a strong typed language. To change one type to another, you need to cast it first:
Uint32 Character::update(Uint32 interval, void* param)
{
reinterpret_cast<Character* >(param)->render();
/* ... */
}
Just for reference, if you were to call a lot of stuff in a function, to save all the nasty reinterpret_cast stuff everywhere you can do
Character * myCharacter = reinterpret_cast<Character* >(param);
Which then lets you do 'myCharacter->render();' or whathaveyou...
精彩评论