I see you've already accepted an answer, but since GTK has an elegant mechanism for dealing with all this, I feel compelled to write another one anyway.
gtk_combo_box_new()
uses malloc()
internally to allocate the pointer it returns. (Well, strictly speaking, that's not true, but let's not be confusing here.) So your GtkComboBox
will be alive until its parent widget is destroyed, or it is removed from its parent widget, or until you destroy it manually (with gtk_widget_destroy()
, not free()
). So, the widget lives on in the background, but the problem is having a pointer to it available where you need it.
Usually you will want to manipulate the combo box in response to a signal, since most of the work in a GTK program is done in signal handlers. If it's one of the combo box's own signals, like the changed
signal, then the callback will be a function like this:
void on_combo_box_changed(GtkComboBox *combo_box, gpointer user_data)
and combo_box
will be the pointer to your combo box.
If you want to manipulate the combo box in response to another widget's signal, let's say a button's clicked
signal, then the callback will be a function like this:
void on_button_clicked(GtkButton *button, gpointer user_data)
As you can see, there is no pointer to the combo box here. Here is where the user_data
parameter comes in. I assume you are connecting your signals in the function where you construct your widgets and pack them into your main window. (If you're not, you should be.) In that function, you will have pointers to both the button and the combo box available. Connect your signal like this...
g_signal_connect(button, "clicked", G_CALLBACK(on_button_clicked), combo_box);
...passing combo_box
as the user_data
parameter to g_signal_connect()
. Then the pointer to the combo box will be passed to the on_button_clicked()
callback, disguised as the user_data
parameter. You can then access it like this:
void on_button_clicked(GtkButton *button, gpointer user_data)
{
GtkComboBox *combo_box = GTK_COMBO_BOX(user_data);
gint item = gtk_combo_box_get_active(combo_box);
etc.
or, due to the way the call stack works in C, even by declaring your callback like this:
void on_button_clicked(GtkButton *button, GtkComboBox *combo_box)
...although then you lose the type-checking cast that GTK_COMBO_BOX()
gives you.