Callbacks...

Started by
4 comments, last by WarMuuh 16 years, 9 months ago
Im writing a small GUI library for my game and i want to have a function(eg SetCallBack(...callback...)) that takes a parameter as a callback and then when you click on a button for example then the GUI library will call the function specified in the SetCallBack function. The problem is i dont have a clue how to do it? Can someone please tell me or give a link to a tutorial on this please Thanks
Advertisement
You want to look into function pointers, or the more OOP-version; Functors.

Example of a function pointer:
// Declare a pointer to a function that returns an int, and takes two parameters (and int and a void).// We tyepdef this as LPSomeFunc.typedef int (*LPSomeFunc)(int nSomething, void* pContext);// Example of calling the function pointer (callback):void SomethingToCallCallback(LPSomeFunc pfnCallback, void* pContext){   for(int i=0; i<10; ++i)   {      pfnCallback(i, pContext);   }}// Example usage of the above function:int MyCallback(int nSomething, void* pContext){   printf("Callback with nSomething = %d\n", nSomething);}SomethingToCallCallback(MyCallback, NULL);

The pContext stuff isn't really used in my example, but you'll see a lot of code takes a user context parameter, so you can pass other data to your callback without having to use a global or something similar, so I've included it for reference.
Thanks alot!
Everything you ever wanted to know about function pointers is documented here. Including code snippets and explanations of why things work (and don't work).

Alan
"There will come a time when you believe everything is finished. That will be the beginning." -Louis L'Amour
Mandatory Links: Boost.Function, Boost.Bind, Boost.Lambda.

Also have a look at std::mem_fn and std::bind1st, std::bind2nd.

Example: Boost.bind + Boost.function + Boost.assign + Boost.foreach
#include <boost/bind.hpp>#include <boost/function.hpp>#include <boost/assign.hpp>#include <boost/foreach.hpp>#include <vector>#include <string>#include <iostream>#define foreach BOOST_FOREACHstruct button{    typedef boost::function<void (button&)> click_event_t;    // just for the example to cause a click event.    void click()     {         foreach(click_event_t& click_event, on_click)        {            click_event(*this);        }    }    std::vector<click_event_t> on_click;};void display_buy_item_message(button&, std::string item_name, unsigned int cost){    // some complex operation.    std::cout << "You have purchased one " << item_name << " at a cost of " << cost << " gold.";}int main(){    button buy_potion, buy_sword;    buy_potion.on_click += boost::bind(display_buy_item_message, _1, "potion", 300);    but_sword.on_click += boost::bind(display_buy_item_message, _1, "sword", 1000);    buy_potion.click();    but_sword.click();}

}
you may take a look at this one:
http://boost.org/doc/html/signals.html

This topic is closed to new replies.

Advertisement