22 May 2005 TazForEver   » (Journeyer)

GObject *_get_type() + G_GNUC_CONST

When you define your own GObject class, you have to define 2 casts macro (instance cast and class cast). So you write :

#define MY_TYPE (My_Type_get_type())
#define MY_TYPE(inst) (G_TYPE_CHECK_INSTANCE_CAST((inst), MY_TYPE, My_Type))

e.g :
#define GTK_TYPE_LABEL (gtk_label_get_type ())

Now have a look at My_Type_get_type() declaration and definition. My_Type_get_type() always return the same GType. So if you write multiple cast, only one call to My_Type_get_type() is really necessary. But gcc is a good servant and does what you ask him : calls My_Type_get_type() whenever you call it. Think about this kind of loop :

for( ... ) {
    GtkWidget* widget= ...;
    gtk_box_pack_start(GTK_BOX(hbox), widget, ...);

To avoid such a waste, you have to tell gcc that all calls to My_Type_get_type() return the same GType.

GType My_Type_get_type (void) G_GNUC_CONST;

GType gtk_label_get_type (void) G_GNUC_CONST;

Yes, it's that simple. Just add a G_GNUC_CONST attribute, and gcc will optimize all your to My_Type_get_type(), therefore all your MY_TYPE(inst).

Be smart, don't forget G_GNUC_CONST when you create your GObject class :)
Of course, glib and gtk+ already do this kind of optimization.

Latest blog entries     Older blog entries

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!