Jump to content
  • Advertisement
Sign in to follow this  

Callback functions

This topic is 5163 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

What are callback functions and why do you need them ? I looked at a couple of places but couldn't get a definite answer. Would someone be kind enuff to give an intro (along with a lil snippet of code ;-) )

Share this post

Link to post
Share on other sites
Callbacks ar eusually used to perfrom some task with the occurance of some event. They are also used commonly to generalize certain operations, and they are usually implemented with function pointers. That is you'd setup a pointer that points to some function depending on the situation. Then the function is called through the pointer and you can have that function change it's operation at runtime.

As for an example, take the windows messaging system. When Windows receives a message it needs to process it. Every application will have it's own way of processing. For example when windows receives an escape key press, what's an application to do. One app might simply exit, another app might pop up a message box asking for confirmation before exiting, and another might not do anything.

So the problem arises, how do you let the application programmer specify what to do on an escape key press? The solution windows uses is a callback function.

You'd make a function according to the signature that windows expects the callback to be in. Standard windows creating involves a callback that returns the type 'LRESULT' and takes in 4 parameters - an HWND, a UINT, an LPARAM and a WPARAM.

Say that pfn is a pointer to this type of function, and say you define your function like so:

LRESULT mymessagecallback( HWND h, UINT msg, WPARAM wp, LPARAM lp )
if( wp == VK_ESCAPE )
// do something;
return 0;

Then youd set a pfn to point to this particular function:

pfn = mymessagecallback

Now when windows receives a message it will not call mymessagecallback directly, instead it calls pfn and supplies that with the parameters it expects. That way you can have different mymessagecallbacks for different windows, each implementation handles messages differently.

so placing a call to:

pfn( hwnd, WM_KEYDOWN, VK_ESCAPE, 0 );

would in effect call:

mymessagecallback( hwnd, WM_KEYDOWN, VK_ESCAPE, 0 );

I think I may have stuffed too much in there, I hope it's cleared at least a few things up.

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!