pdm
pdm

Reputation: 1107

"Correct" casting for g_signal_connect() using GTK?

g_signal_connect() expects a gpointer, a character constant, a GCallback, and another gpointer as parameters.

I'm reading through the Foundations of GTK+ book right now and it just occurred to me that the author tends to cast the first parameter as a G_OBJECT and the last as a (gpointer), even though both are defined as gpointer's in the function signature and both parameters are GtkWidgets.

So, which (if either) is the most appropriate cast for this function? It seems strange to use two different casts.

Upvotes: 1

Views: 1498

Answers (3)

iain
iain

Reputation: 5683

In addition to the other answers: it is a remnant from the old Gtk+ 1 days when the function was gtk_signal_connect and it took a GtkObject as the first argument.

Upvotes: 1

ebassi
ebassi

Reputation: 8805

you don't have to use the G_OBJECT() cast macro for the first parameter: the GSignal API does not require GObject — it can be use with any GTypeInstance implementation.

you also don't need to cast to gpointer the last parameter, unless you're using a C++ compiler; gpointer is a typedef to void *, and the cast between pointer-sized types and void * is implicit in C.

Upvotes: 2

Tristan Brindle
Tristan Brindle

Reputation: 16824

A minor point, but g_signal_connect() is actually a macro which calls g_signal_connect_data() -- not that it really makes any difference. The parameter types you've listed are correct, though.

In C, any pointer type can be implicitly converted to a void* (aka gpointer), so no explicit casts are required at all. Indeed, the whole reason that the first parameter has type gpointer rather than GObject* is to save you having to do a manual cast. I haven't seen the book, but it strikes me that the convention the author has settled upon is rather... unusual, to say the least. I don't think I've seen any GObject code "in the wild" where this is done.

As an aside, if you are connecting one GObject to another -- for example, if the recipient of a signal is a GtkWidget -- then it's better to use g_signal_connect_object() rather than a plain g_signal_connect(). If you do this, it will ensure that the signal is automatically disconnected when the receiving object is destroyed, which otherwise you would need to handle manually in the receiver's destructor.

Hope this helps!

Upvotes: 1

Related Questions