Recently I’ve started a C++ project in order to skill myself with GTK functions. I’ve used C++ approach ’cause i always programmed in java, so it seems to me much familiar.
Now, GTK libraries are written in C code, so i achieved some mix between classes and C codestyle. One of my issues is that GTK events works with callback functions. To encapsulate those event in classes I made use of static methods.
The big deal is that static methods and static variables are not visible from inside the class, plus I’ve written some other static functions, declared only in the .cpp file of the class, called from inside the callbacks but completely separated from the class.
It seems to me this approach is a bit clumsy, so I wonder is there any best approach in order to handle those callbacks in classes and allow them to interact with class methods and structures in an elegant way?
Thanks!
Yes, you need to pass the state (For instance you this pointer, or a pointer to some slot/functor) in the user_data parameter. Otherwise, you will never have a class instance with which to call your member method.
This is what gtkmm does. For instance, Gtk::Container::foreach() uses a static (non member) function, passing a provided sigc::slot to it:
http://git.gnome.org/browse/gtkmm/tree/gtk/src/container.ccg#n166
The code for signals (what you call events in your question) is similar, but slightly more complicated – you can see that in the generated .cc code in gtkmm.
But, I also think that you should just use gtkmm. This is just one of several problems that you would otherwise end up (not) solving yourself.