1. accessing C union members...
- Posted by ssallen Jan 10, 2013
- 1260 views
Hello, I am trying to access a C union in a dll. The Union looks like this:
typedef union{ Uint8 type; SDL_ActiveEvent active; SDL_KeyboardEvent key; SDL_MouseMotionEvent motion; SDL_MouseButtonEvent button; SDL_JoyAxisEvent jaxis; SDL_JoyBallEvent jball; SDL_JoyHatEvent jhat; SDL_JoyButtonEvent jbutton; SDL_ResizeEvent resize; SDL_ExposeEvent expose; SDL_QuitEvent quit; SDL_UserEvent user; SDL_SywWMEvent syswm; } SDL_Event;
First, I want to check that type equals a certain value then I need to access the SDL_MouseButtonEvent member. It looks like so:
typedef struct{ Uint8 type; Uint8 which; Uint8 button; Uint8 state; Uint16 x, y; } SDL_MouseButtonEvent;
Here is my code:
global function viewScrollWheel() atom sdl_event integer mwheel, etype, button etype = 0 button = 0 sdl_event = allocate(100) -- allocate enough memory for event structure while(SDL_PollEvent(sdl_event)) do -- loop thru events etype = peek(sdl_event) --get type member from event? if etype = SDL_MOUSEBUTTONDOWN then -- if type = MBD then button = 1 -- making sure we are here... exit end if end while free(sdl_event) return button end function
I want to check the type field in the event union and if it equals SDL_MOUSEBUTTONDOWN then I want to check the button field that is part of the struct. Any help is appreciated!
2. Re: accessing C union members...
- Posted by mattlewis (admin) Jan 10, 2013
- 1124 views
I want to check the type field in the event union and if it equals SDL_MOUSEBUTTONDOWN then I want to check the button field that is part of the struct. Any help is appreciated!
It looks like you're doing the detection of SDL_MOUSEBUTTONDOWN correctly. The button should be at sdl_event + 2, so you should be able to read it with peek( sdl_event + 2 ).
Matt
3. Re: accessing C union members...
- Posted by gbonvehi Jan 10, 2013
- 1089 views
Adding to what Matt said:
The union type tells basically that it can contain any of the types specified in it's declaration. Don't get confused, it will only hold one value at a time, either a type (Uint8), a key (SDL_KeyboardEvent), a jaxis (SDL_JoyAxisEvent), etc.
A Uint8 type uses 1 byte in memory (8-bits). Knowing this and that the initial offset is 0, you can calculate the offsets you will need for each var in the event structure:
typedef struct{ Uint8 type; Uint8 which; Uint8 button; Uint8 state; Uint16 x, y; } SDL_MouseButtonEvent;
peek(sdl_event) -- type peek(sdl_event+1) -- which peek(sdl_event+2) -- button peek(sdl_event+3) -- state peek2u(sdl_event+4) -- x peek2u(sdl_event+6) -- y (Uint16 takes 2 bytes in memory)
Cheers,
Guillermo
4. Re: accessing C union members...
- Posted by ssallen Jan 10, 2013
- 1065 views
Thanks, the code wasn't working and I was pretty puzzled. Found out that I was clearing the variable in another part of the code. All is working correctly now.
Thanks!