Can anyone translate this for me please?
Hi,
I''m new to these forums, and just embarking on my first game. I know I have a fair way to go, but I''ve read through Code on the Cob and am using that as a starting point.
I''ve come across this bit of code that is (I think) to do with function pointers. It implements an event handler callback function for use with DirectInput. I can''t quite comprehend the function prototype definition and was hoping that someone here may be able to explain it for me. Here it is:
static void (*inputw_eventHandler)(input_event_t *) = NULL;
Some backgroud - input_event_t is a typedef struct
This is my interpretation of it, as well as some details about how it''s used:
//THIS IS HOW THIS FUNCTION IS USED:
//ReceiverDispatch function is as follows:
static void ReceiverDispatch(input_event_t *event)
{}
//(i) INPUT_Init() in INPUT_main.cpp calls INPUTW_SetEventHandler(ReceiverDispatch)
//where ReceiverDispatch is another function - ie we PASS a function!
//(ii) INPUTW_SetEventHandler accepts as input a void function pointer called handler
//then inputw_eventHandler is set to handler - ie. now inputeventHandler points at ReceiverDispatch
void INW_SetEventHandler(void (*handler)(in_event_t *))
{
inw_eventHandler = handler;
}
//(iii) Now when inputw_eventHandler is called (and is valid) it passes a pointer to the event structure
//indirectly to the ReceiverDispatch function in INPUT_main.cpp. PHEW!!!!
if (inputw_eventHandler)
inputw_eventHandler(event);
Hope you guys can follow me on this!! If any more details are required, please email me on mboulton@bigpond.net.au
Thanks,
Mark.
static void (*inputw_eventHandler)(input_event_t *) = NULL;
The function pointer is intialized to NULL. This would point to a function like ReceiverDispatch. Notice the similarity with the prototype for ReceiverDispatch:
static void ReceiverDispatch(input_event_t *event);
The function isn''t actually passed, a pointer to the function is passed. Quick sort routines do this also.
void INW_SetEventHandler(void (*handler)(in_event_t *)){ inw_eventHandler = handler;}
Here the function pointer is assigned a function to point to. Notice the similarity between the parameter type, the function pointer and the prototype for ReceiverDispatch.
INPUTW_SetEventHandler(ReceiverDispatch) assigns ReceiverDispatch to the inw_eventHandler pointer. inw_eventHandler can now be used to invoke the code inside ReceiverDispatch.
if (inputw_eventHandler) inputw_eventHandler(event);
If inputw_eventHandler points to ReceiverDispatch, this is the same as calling ReceiverDispatch(event).
This kind of set up is used to make it easier to switch event handlers. You could have several ReceiverDispatch functions, (ie ReceiverDispatch0, ReceiverDispatch1, ReceiverDispatch2,... ) but only one interface to call them with - so long as you set the handler to the one you want before hand.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement