是的,它会起作用,记住SDL_Event
结构本身是一个很大的union
. 你是对的,如果你不确定你的结构是否适合SDL_Event
你可以添加这个编译时断言:sizeof(UserEvent_MapCollision) <= sizeof(SDL_Event)
。
/* Push event */
SDL_Event e;
UserEvent_MapCollision* p = static_cast<UserEvent_MapCollision*>(&e);;
e.type = SDL_USEREVENT + MAP;
e.code = MAP_COLLISION;
p.tile_x = 10;
p.tile_y = 20;
p.tile_type = 7;
/* Receive event */
SDL_Event e;
while (SDL_PollEvents(&e)) {
if (e.type == SDL_USEREVENT + MAP) {
if (e.user.code == MAP_COLLISION) {
UserEvent_MapCollision *p = static_cast<UserEvent_MapCollision>(&e)
HandleMapCollision(p);
}
}
}
要在编译时检查断言,您可以使用 SDL 宏SDL_COMPILE_TIME_ASSERT
,它定义在SDL_stdinc.h
:
SDL_COMPILE_TIME_ASSERT(UserEvent_MapCollision, sizeof(UserEvent_MapCollision) <= sizeof(SDL_Event));
作为旁注,这两个void*
指针旨在引用另一个结构。
typedef struct {
Uint8 tile_x;
Uint8 tile_y;
Uint8 tile_type;
} MyCustomEventStruct;
/* Create event */
SDL_UserEvent e;
MyCustomEventStruct *p;
p = new MyCustomEventStruct;
p->tile_x = 10;
p->tile_y = 20;
p->tile_type = 7;
e.type = SDL_USEREVENT + MAP;
e.code = MAP_COLLISION;
e.data1 = p;
e.data2 = 0;
SDL_PushEvent(&e);
/* Receive Event */
while (SDL_PollEvents(&e)) {
if (e.type == SDL_USEREVENT + MAP) {
if (e.user.code == MAP_COLLISION) {
MyCustomEventStruct* p = static_cast<MyCustomEventStruct*>(e.user.data1);
HandleMapCollision(p);
delete p;
}
}
}