1

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!

1
  • @JoachimPileborg: I suggest that you post your comment as an answer.
    – wilx
    Apr 20, 2012 at 7:46

3 Answers 3

6

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.

1
  • Funnily, one of my projects uses gtkmm and another C++ library, but the latter has C-style callbacks, so I have to go via userdata there. Makes me appreciate gtkmm even more :-) Thanks for all the work on it. I like GTK+ for C but couldn't face using it with C++, so if not for gtkmm, I'd probably have had to find another toolkit - thus losing all the cool stuff GTK offers. Dec 6, 2015 at 0:59
3

I recommend you look into Gtkmm instead.

2

As a sidenote, GTK libraries are written in C, but there are bindings to use them from other languages:

  • C++ → GTKmm
  • python → pyGTK (for GTK2), pyGObject (for GTK3)
  • Java → java-gnome

etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.