1 <?xml version='1.0' encoding="ISO-8859-1"?>
2 <!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN"
3 "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
5 <chapter id="chapter-gobject">
6 <title>The GObject base class</title>
9 The previous chapter discussed the details of GLib's Dynamic Type System.
10 The GObject library also contains an implementation for a base fundamental
11 type named <link linkend="GObject"><type>GObject</type></link>.
15 <link linkend="GObject"><type>GObject</type></link> is a fundamental classed instantiable type. It implements:
17 <listitem><para>Memory management with reference counting</para></listitem>
18 <listitem><para>Construction/Destruction of instances</para></listitem>
19 <listitem><para>Generic per-object properties with set/get function pairs</para></listitem>
20 <listitem><para>Easy use of signals</para></listitem>
22 All the GNOME libraries which use the GLib type system (like GTK+ and GStreamer)
23 inherit from <link linkend="GObject"><type>GObject</type></link> which is why it is important to understand
24 the details of how it works.
27 <sect1 id="gobject-instantiation">
28 <title>Object instantiation</title>
31 The <function><link linkend="g-object-new">g_object_new</link></function>
32 family of functions can be used to instantiate any GType which inherits
33 from the GObject base type. All these functions make sure the class and
34 instance structures have been correctly initialized by GLib's type system
35 and then invoke at one point or another the constructor class method
39 Allocate and clear memory through <function><link linkend="g-type-create-instance">g_type_create_instance</link></function>,
42 Initialize the object's instance with the construction properties.
45 Although one can expect all class and instance members (except the fields
46 pointing to the parents) to be set to zero, some consider it good practice
47 to explicitly set them.
51 Objects which inherit from GObject are allowed to override this
52 constructor class method: they should however chain to their parent
53 constructor method before doing so:
55 GObject *(* constructor) (GType gtype,
57 GObjectConstructParam *properties);
62 The example below shows how <type>MamanBar</type> overrides the parent's constructor:
64 #define MAMAN_TYPE_BAR (maman_bar_get_type ())
65 #define MAMAN_BAR(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_TYPE_BAR, MamanBar))
66 #define MAMAN_IS_BAR(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_TYPE_BAR))
67 #define MAMAN_BAR_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), MAMAN_TYPE_BAR, MamanBarClass))
68 #define MAMAN_IS_BAR_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), MAMAN_TYPE_BAR))
69 #define MAMAN_BAR_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), MAMAN_TYPE_BAR, MamanBarClass))
71 typedef struct _MamanBar MamanBar;
72 typedef struct _MamanBarClass MamanBarClass;
76 GObject parent_instance;
78 /* instance members */
83 GObjectClass parent_class;
88 /* will create maman_bar_get_type and set maman_bar_parent_class */
89 G_DEFINE_TYPE (MamanBar, maman_bar, G_TYPE_OBJECT);
92 maman_bar_constructor (GType gtype,
94 GObjectConstructParam *properties)
99 /* Always chain up to the parent constructor */
100 obj = G_OBJECT_CLASS (maman_bar_parent_class)->constructor (gtype, n_properties, properties);
103 /* update the object state depending on constructor properties */
109 maman_bar_class_init (MamanBarClass *klass)
111 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
113 gobject_class->constructor = maman_bar_constructor;
117 maman_bar_init (MamanBar *self)
119 /* initialize the object */
123 If the user instantiates an object <type>MamanBar</type> with:
125 MamanBar *bar = g_object_new (MAMAN_TYPE_BAR, NULL);
127 If this is the first instantiation of such an object, the
128 <function>maman_bar_class_init</function> function will be invoked
129 after any <function>maman_bar_base_class_init</function> function.
130 This will make sure the class structure of this new object is
131 correctly initialized. Here, <function>maman_bar_class_init</function>
132 is expected to override the object's class methods and setup the
133 class' own methods. In the example above, the constructor method is
134 the only overridden method: it is set to
135 <function>maman_bar_constructor</function>.
139 Once <function><link linkend="g-object-new">g_object_new</link></function> has obtained a reference to an initialized
140 class structure, it invokes its constructor method to create an instance of the new
141 object. Since it has just been overridden by <function>maman_bar_class_init</function>
142 to <function>maman_bar_constructor</function>, the latter is called and, because it
143 was implemented correctly, it chains up to its parent's constructor. In
144 order to find the parent class and chain up to the parent class
145 constructor, we can use the <literal>maman_bar_parent_class</literal>
146 pointer that has been set up for us by the
147 <literal>G_DEFINE_TYPE</literal> macro.
151 Finally, at one point or another, <function>g_object_constructor</function> is invoked
152 by the last constructor in the chain. This function allocates the object's instance' buffer
153 through <function><link linkend="g-type-create-instance">g_type_create_instance</link></function>
154 which means that the instance_init function is invoked at this point if one
155 was registered. After instance_init returns, the object is fully initialized and should be
156 ready to answer any user-request. When <function><link linkend="g-type-create-instance">g_type_create_instance</link></function>
157 returns, <function>g_object_constructor</function> sets the construction properties
158 (i.e. the properties which were given to <function><link linkend="g-object-new">g_object_new</link></function>) and returns
159 to the user's constructor which is then allowed to do useful instance initialization...
163 The process described above might seem a bit complicated, but it can be
164 summarized easily by the table below which lists the functions invoked
165 by <function><link linkend="g-object-new">g_object_new</link></function>
166 and their order of invocation:
170 <table id="gobject-construction-table">
171 <title><function><link linkend="g-object-new">g_object_new</link></function></title>
173 <colspec colwidth="*" colnum="1" align="left"/>
174 <colspec colwidth="*" colnum="2" align="left"/>
175 <colspec colwidth="8*" colnum="3" align="left"/>
179 <entry>Invocation time</entry>
180 <entry>Function Invoked</entry>
181 <entry>Function's parameters</entry>
182 <entry>Remark</entry>
187 <entry morerows="3">First call to <function><link linkend="g-object-new">g_object_new</link></function> for target type</entry>
188 <entry>target type's base_init function</entry>
189 <entry>On the inheritance tree of classes from fundamental type to target type.
190 base_init is invoked once for each class structure.</entry>
192 I have no real idea on how this can be used. If you have a good real-life
193 example of how a class' base_init can be used, please, let me know.
197 <!--entry>First call to <function><link linkend="g-object-new">g_object_new</link></function> for target type</entry-->
198 <entry>target type's class_init function</entry>
199 <entry>On target type's class structure</entry>
201 Here, you should make sure to initialize or override class methods (that is,
202 assign to each class' method its function pointer) and create the signals and
203 the properties associated to your object.
207 <!--entry>First call to <function><link linkend="g-object-new">g_object_new</link></function> for target type</entry-->
208 <entry>interface' base_init function</entry>
209 <entry>On interface' vtable</entry>
213 <!--entry>First call to <function><link linkend="g-object-new">g_object_new</link></function> for target type</entry-->
214 <entry>interface' interface_init function</entry>
215 <entry>On interface' vtable</entry>
219 <entry morerows="1">Each call to <function><link linkend="g-object-new">g_object_new</link></function> for target type</entry>
220 <entry>target type's class constructor method: GObjectClass->constructor</entry>
221 <entry>On object's instance</entry>
223 If you need to complete the object initialization after all the construction properties
224 are set, override the constructor method and make sure to chain up to the object's
225 parent class before doing your own initialization.
226 In doubt, do not override the constructor method.
230 <!--entry>Each call to <function><link linkend="g-object-new">g_object_new</link></function> for target type</entry-->
231 <entry>type's instance_init function</entry>
232 <entry>On the inheritance tree of classes from fundamental type to target type.
233 the instance_init provided for each type is invoked once for each instance
236 Provide an instance_init function to initialize your object before its construction
237 properties are set. This is the preferred way to initialize a GObject instance.
238 This function is equivalent to C++ constructors.
247 Readers should feel concerned about one little twist in the order in
248 which functions are invoked: while, technically, the class' constructor
249 method is called <emphasis>before</emphasis> the GType's instance_init
250 function (since <function><link linkend="g-type-create-instance">g_type_create_instance</link></function> which calls instance_init is called by
251 <function>g_object_constructor</function> which is the top-level class
252 constructor method and to which users are expected to chain to), the
253 user's code which runs in a user-provided constructor will always
254 run <emphasis>after</emphasis> GType's instance_init function since the
255 user-provided constructor <emphasis>must</emphasis> (you've been warned)
256 chain up <emphasis>before</emphasis> doing anything useful.
260 <sect1 id="gobject-memory">
261 <title>Object memory management</title>
264 The memory-management API for GObjects is a bit complicated but the idea behind it
265 is pretty simple: the goal is to provide a flexible model based on reference counting
266 which can be integrated in applications which use or require different memory management
267 models (such as garbage collection). The methods which are used to
268 manipulate this reference count are described below.
273 gpointer g_object_ref (gpointer object);
274 void g_object_unref (gpointer object);
279 typedef void (*GWeakNotify) (gpointer data,
280 GObject *where_the_object_was);
282 void g_object_weak_ref (GObject *object,
285 void g_object_weak_unref (GObject *object,
288 void g_object_add_weak_pointer (GObject *object,
289 gpointer *weak_pointer_location);
290 void g_object_remove_weak_pointer (GObject *object,
291 gpointer *weak_pointer_location);
295 void g_object_run_dispose (GObject *object);
299 <sect2 id="gobject-memory-refcount">
300 <title>Reference count</title>
303 The functions <function><link linkend="g-object-ref">g_object_ref</link></function>/<function><link linkend="g-object-unref">g_object_unref</link></function> respectively
304 increase and decrease the reference count.These functions are thread-safe as of GLib 2.8.
305 The reference count is, unsurprisingly, initialized to one by
306 <function><link linkend="g-object-new">g_object_new</link></function> which means that the caller
307 is currently the sole owner of the newly-created reference.
308 When the reference count reaches zero, that is,
309 when <function><link linkend="g-object-unref">g_object_unref</link></function> is called by the last client holding
310 a reference to the object, the <emphasis>dispose</emphasis> and the
311 <emphasis>finalize</emphasis> class methods are invoked.
314 Finally, after <emphasis>finalize</emphasis> is invoked,
315 <function><link linkend="g-type-free-instance">g_type_free_instance</link></function> is called to free the object instance.
316 Depending on the memory allocation policy decided when the type was registered (through
317 one of the <function>g_type_register_*</function> functions), the object's instance
318 memory will be freed or returned to the object pool for this type.
319 Once the object has been freed, if it was the last instance of the type, the type's class
320 will be destroyed as described in <xref linkend="gtype-instantiable-classed"/> and
321 <xref linkend="gtype-non-instantiable-classed"/>.
325 The table below summarizes the destruction process of a GObject:
326 <table id="gobject-destruction-table">
327 <title><function><link linkend="g-object-unref">g_object_unref</link></function></title>
329 <colspec colwidth="*" colnum="1" align="left"/>
330 <colspec colwidth="*" colnum="2" align="left"/>
331 <colspec colwidth="8*" colnum="3" align="left"/>
335 <entry>Invocation time</entry>
336 <entry>Function Invoked</entry>
337 <entry>Function's parameters</entry>
338 <entry>Remark</entry>
343 <entry morerows="1">Last call to <function><link linkend="g-object-unref">g_object_unref</link></function> for an instance
346 <entry>target type's dispose class function</entry>
347 <entry>GObject instance</entry>
349 When dispose ends, the object should not hold any reference to any other
350 member object. The object is also expected to be able to answer client
351 method invocations (with possibly an error code but no memory violation)
352 until finalize is executed. dispose can be executed more than once.
353 dispose should chain up to its parent implementation just before returning
358 <!--entry>Last call to <function><link linkend="g-object-unref">g_object_unref</link></function> for an instance
361 <entry>target type's finalize class function</entry>
362 <entry>GObject instance</entry>
364 Finalize is expected to complete the destruction process initiated by
365 dispose. It should complete the object's destruction. finalize will be
367 finalize should chain up to its parent implementation just before returning
369 The reason why the destruction process is split is two different phases is
370 explained in <xref linkend="gobject-memory-cycles"/>.
374 <entry morerows="3">Last call to <function><link linkend="g-object-unref">g_object_unref</link></function> for the last
375 instance of target type
377 <entry>interface' interface_finalize function</entry>
378 <entry>On interface' vtable</entry>
379 <entry>Never used in practice. Unlikely you will need it.</entry>
382 <!--entry>Last call to <function><link linkend="g-object-unref">g_object_unref</link></function>for the last
383 instance of target type
385 <entry>interface' base_finalize function</entry>
386 <entry>On interface' vtable</entry>
387 <entry>Never used in practice. Unlikely you will need it.</entry>
390 <!--entry>Last call to <function><link linkend="g-object-unref">g_object_unref</link></function> for the last
391 instance of target type
393 <entry>target type's class_finalize function</entry>
394 <entry>On target type's class structure</entry>
395 <entry>Never used in practice. Unlikely you will need it.</entry>
398 <!--entry>Last call to <function><link linkend="g-object-unref">g_object_unref</link></function> for the last
399 instance of target type
401 <entry>type's base_finalize function</entry>
402 <entry>On the inheritance tree of classes from fundamental type to target type.
403 base_init is invoked once for each class structure.</entry>
404 <entry>Never used in practice. Unlikely you will need it.</entry>
413 <sect2 id="gobject-memory-weakref">
414 <title>Weak References</title>
417 Weak References are used to monitor object finalization:
418 <function><link linkend="g-object-weak-ref">g_object_weak_ref</link></function> adds a monitoring callback which does
419 not hold a reference to the object but which is invoked when the object runs
420 its dispose method. As such, each weak ref can be invoked more than once upon
421 object finalization (since dispose can run more than once during object
426 <function><link linkend="g-object-weak-unref">g_object_weak_unref</link></function> can be used to remove a monitoring
427 callback from the object.
431 Weak References are also used to implement <function><link linkend="g-object-add-weak-pointer">g_object_add_weak_pointer</link></function>
432 and <function><link linkend="g-object-remove-weak-pointer">g_object_remove_weak_pointer</link></function>. These functions add a weak reference
433 to the object they are applied to which makes sure to nullify the pointer given by the user
434 when object is finalized.
439 <sect2 id="gobject-memory-cycles">
440 <title>Reference counts and cycles</title>
443 Note: the following section was inspired by James Henstridge. I guess this means that
444 all praise and all curses will be directly forwarded to him.
448 GObject's memory management model was designed to be easily integrated in existing code
449 using garbage collection. This is why the destruction process is split in two phases:
450 the first phase, executed in the dispose handler is supposed to release all references
451 to other member objects. The second phase, executed by the finalize handler is supposed
452 to complete the object's destruction process. Object methods should be able to run
453 without program error (that is, without segfault :) in-between the two phases.
457 This two-step destruction process is very useful to break reference counting cycles.
458 While the detection of the cycles is up to the external code, once the cycles have been
459 detected, the external code can invoke <function><link linkend="g-object-run-dispose">g_object_run_dispose</link></function> which
460 will indeed break any existing cycles since it will run the dispose handler associated
461 to the object and thus release all references to other objects.
465 Attentive readers might now have understood one of the rules about the dispose handler
466 we stated a bit sooner: the dispose handler can be invoked multiple times. Let's say we
467 have a reference count cycle: object A references B which itself references object A.
468 Let's say we have detected the cycle and we want to destroy the two objects. One way to
469 do this would be to invoke <function><link linkend="g-object-run-dispose">g_object_run_dispose</link></function> on one of the
474 If object A releases all its references to all objects, this means it releases its
475 reference to object B. If object B was not owned by anyone else, this is its last
476 reference count which means this last unref runs B's dispose handler which, in turn,
477 releases B's reference on object A. If this is A's last reference count, this last
478 unref runs A's dispose handler which is running for the second time before
479 A's finalize handler is invoked !
483 The above example, which might seem a bit contrived can really happen if your
484 GObject's are being handled by language bindings. I would thus suggest the rules stated above
485 for object destruction are closely followed. Otherwise, <emphasis>Bad Bad Things</emphasis>
491 <sect1 id="gobject-properties">
492 <title>Object properties</title>
495 One of GObject's nice features is its generic get/set mechanism for object
496 properties. When an object
497 is instantiated, the object's class_init handler should be used to register
498 the object's properties with <function><link linkend="g-object-class-install-properties">g_object_class_install_properties</link></function>
499 (implemented in <filename>gobject.c</filename>).
503 The best way to understand how object properties work is by looking at a real example
505 <informalexample><programlisting>
506 /************************************************/
508 /************************************************/
520 static GParamSpec *obj_properties[N_PROPERTIES] = { NULL, };
523 maman_bar_set_property (GObject *object,
528 MamanBar *self = MAMAN_BAR (object);
532 case PROP_MAMAN_NAME:
533 g_free (self->priv->name);
534 self->priv->name = g_value_dup_string (value);
535 g_print ("maman: %s\n", self->priv->name);
538 case PROP_PAPA_NUMBER:
539 self->priv->papa_number = g_value_get_uchar (value);
540 g_print ("papa: %u\n", self->priv->papa_number);
544 /* We don't have any other property... */
545 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
551 maman_bar_get_property (GObject *object,
556 MamanBar *self = MAMAN_BAR (object);
560 case PROP_MAMAN_NAME:
561 g_value_set_string (value, self->priv->name);
564 case PROP_PAPA_NUMBER:
565 g_value_set_uchar (value, self->priv->papa_number);
569 /* We don't have any other property... */
570 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
576 maman_bar_class_init (MamanBarClass *klass)
578 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
580 gobject_class->set_property = maman_bar_set_property;
581 gobject_class->get_property = maman_bar_get_property;
583 obj_properties[PROP_NAME] =
584 g_param_spec_string ("maman-name",
585 "Maman construct prop",
587 "no-name-set" /* default value */,
588 G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE);
590 obj_properties[PROP_NUMBER] =
591 g_param_spec_uchar ("papa-number",
592 "Number of current Papa",
593 "Set/Get papa's number",
594 0 /* minimum value */,
595 10 /* maximum value */,
596 2 /* default value */,
599 g_object_class_install_properties (gobject_class,
604 /************************************************/
606 /************************************************/
609 GValue val = G_VALUE_INIT;
611 bar = g_object_new (MAMAN_TYPE_SUBBAR, NULL);
613 g_value_init (&val, G_TYPE_CHAR);
614 g_value_set_char (&val, 11);
616 g_object_set_property (G_OBJECT (bar), "papa-number", &val);
618 g_value_unset (&val);
619 </programlisting></informalexample>
620 The client code just above looks simple but a lot of things happen under the hood:
624 <function><link linkend="g-object-set-property">g_object_set_property</link></function> first ensures a property
625 with this name was registered in bar's class_init handler. If so it walks the class hierarchy,
626 from bottom, most derived type, to top, fundamental type to find the class
627 which registered that property. It then tries to convert the user-provided GValue
628 into a GValue whose type is that of the associated property.
632 If the user provides a signed char GValue, as is shown
633 here, and if the object's property was registered as an unsigned int,
634 <function><link linkend="g-value-transform">g_value_transform</link></function> will try to transform the input signed char into
635 an unsigned int. Of course, the success of the transformation depends on the availability
636 of the required transform function. In practice, there will almost always be a transformation
638 <para>Its behaviour might not be what you expect but it is up to you to actually avoid
639 relying on these transformations.
642 which matches and conversion will be carried out if needed.
646 After transformation, the <link linkend="GValue"><type>GValue</type></link> is validated by
647 <function><link linkend="g-param-value-validate">g_param_value_validate</link></function> which makes sure the user's
648 data stored in the <link linkend="GValue"><type>GValue</type></link> matches the characteristics specified by
649 the property's <link linkend="GParamSpec"><type>GParamSpec</type></link>.
650 Here, the <link linkend="GParamSpec"><type>GParamSpec</type></link> we
651 provided in class_init has a validation function which makes sure that the GValue
652 contains a value which respects the minimum and maximum bounds of the
653 <link linkend="GParamSpec"><type>GParamSpec</type></link>. In the example above, the client's GValue does not
654 respect these constraints (it is set to 11, while the maximum is 10). As such, the
655 <function><link linkend="g-object-set-property">g_object_set_property</link></function> function will return with an error.
659 If the user's GValue had been set to a valid value, <function><link linkend="g-object-set-property">g_object_set_property</link></function>
660 would have proceeded with calling the object's set_property class method. Here, since our
661 implementation of Foo did override this method, the code path would jump to
662 <function>foo_set_property</function> after having retrieved from the
663 <link linkend="GParamSpec"><type>GParamSpec</type></link> the <emphasis>param_id</emphasis>
666 It should be noted that the param_id used here need only to uniquely identify each
667 <link linkend="GParamSpec"><type>GParamSpec</type></link> within the <type>FooClass</type> such that the switch
668 used in the set and get methods actually works. Of course, this locally-unique
669 integer is purely an optimization: it would have been possible to use a set of
670 <emphasis>if (strcmp (a, b) == 0) {} else if (strcmp (a, b) == 0) {}</emphasis> statements.
673 which had been stored by
674 <function><link linkend="g-object-class-install-property">g_object_class_install_property</link></function>.
678 Once the property has been set by the object's set_property class method, the code path
679 returns to <function><link linkend="g-object-set-property">g_object_set_property</link></function> which makes sure that
680 the "notify" signal is emitted on the object's instance with the changed property as
681 parameter unless notifications were frozen by <function><link linkend="g-object-freeze-notify">g_object_freeze_notify</link></function>.
685 <function><link linkend="g-object-thaw-notify">g_object_thaw_notify</link></function> can be used to re-enable notification of
686 property modifications through the "notify" signal. It is important to remember that
687 even if properties are changed while property change notification is frozen, the "notify"
688 signal will be emitted once for each of these changed properties as soon as the property
689 change notification is thawed: no property change is lost for the "notify" signal. Signal
690 can only be delayed by the notification freezing mechanism.
694 It sounds like a tedious task to set up GValues every time when one wants to modify a property.
695 In practice one will rarely do this. The functions <function><link linkend="g-object-set-property">g_object_set_property</link></function>
696 and <function><link linkend="g-object-get-property">g_object_get_property</link></function>
697 are meant to be used by language bindings. For application there is an easier way and
698 that is described next.
701 <sect2 id="gobject-multi-properties">
702 <title>Accessing multiple properties at once</title>
705 It is interesting to note that the <function><link linkend="g-object-set">g_object_set</link></function> and
706 <function><link linkend="g-object-set-valist">g_object_set_valist</link></function> (vararg version) functions can be used to set
707 multiple properties at once. The client code shown above can then be re-written as:
711 g_object_set (G_OBJECT (foo),
713 "maman-name", "test",
716 This saves us from managing the GValues that we were needing to handle when using
717 <function><link linkend="g-object-set-property">g_object_set_property</link></function>.
718 The code above will trigger one notify signal emission for each property modified.
722 Of course, the _get versions are also available: <function><link linkend="g-object-get">g_object_get</link></function>
723 and <function><link linkend="g-object-get-valist">g_object_get_valist</link></function> (vararg version) can be used to get numerous
728 These high level functions have one drawback - they don't provide a return result.
729 One should pay attention to the argument types and ranges when using them.
730 A known source of errors is to e.g. pass a gfloat instead of a gdouble and thus
731 shifting all subsequent parameters by four bytes. Also forgetting the terminating
732 NULL will lead to unexpected behaviour.
736 Really attentive readers now understand how <function><link linkend="g-object-new">g_object_new</link></function>,
737 <function><link linkend="g-object-newv">g_object_newv</link></function> and <function><link linkend="g-object-new-valist">g_object_new_valist</link></function>
738 work: they parse the user-provided variable number of parameters and invoke
739 <function><link linkend="g-object-set">g_object_set</link></function> on the parameters only after the object has been successfully constructed.
740 Of course, the "notify" signal will be emitted for each property set.
745 <!-- @todo tell here about how to pass use handle properties in derived classes -->