How do I attach data to some GTK+ object/widget? [GTK 2.x]

First of all, the attached data is stored in the object_data field of a GtkObject. The type of this field is GData, which is defined in glib.h. So you should read the gdataset.c file in your glib source directory very carefully.

There are two (easy) ways to attach some data to a gtk object. Using g_object_set_data() and g_object_get_data() seems to be the most common way to do this, as it provides a powerful interface to connect objects and data.

void g_object_set_data(GObject *object, const gchar *key, gpointer data);

gpointer g_object_get_data(GObject *object, const gchar *key);

Since a short example is better than any lengthy speech:

struct my_struct	p1,p2,*result;
GtkWidget		*w;

g_object_set_data(G_OBJECT(w),"p1 data",(gpointer)&p1);
g_object_set_data(G_OBJECT(w),"p2 data",(gpointer)&p2);

result = g_object_get_data(G_OBJECT(w),"p1 data");

The gtk_object_set_user_data() and gtk_object_get_user_data() functions does exactly the same thing as the functions above, but does not let you specify the "key" parameter.Instead, it uses a standard "user_data" key. Note that the use of these functions is deprecated in 1.2. They only provide a compatibility mode with some old gtk packages.