1 <?xml version='1.0' encoding="ISO-8859-1"?>
2 <!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
3 "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd" [
5 <chapter id="chapter-gobject">
6 <title>The GObject base class</title>
9 The two previous chapters discussed the details of GLib's Dynamic Type System
10 and its signal control system. The GObject library also contains an implementation
11 for a base fundamental type named <type><link linkend="GObject">GObject</link></type>.
15 <type><link linkend="GObject">GObject</link></type> 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 <type><link linkend="GObject">GObject</link></type> 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 MamanBarClass *klass;
101 GObjectClass *parent_class;
102 parent_class = G_OBJECT_CLASS (maman_bar_parent_class);
103 obj = parent_class->constructor (gtype, n_properties, properties);
106 /* update the object state depending on constructor properties */
112 maman_bar_class_init (MamanBarClass *klass)
114 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
116 gobject_class->constructor = maman_bar_constructor;
120 maman_bar_init (MamanBar *self)
122 /* initialize the object */
126 If the user instantiates an object <type>MamanBar</type> with:
128 MamanBar *bar = g_object_new (MAMAN_TYPE_BAR, NULL);
130 If this is the first instantiation of such an object, the
131 <function>maman_bar_class_init</function> function will be invoked
132 after any <function>maman_bar_base_class_init</function> function.
133 This will make sure the class structure of this new object is
134 correctly initialized. Here, <function>maman_bar_class_init</function>
135 is expected to override the object's class methods and setup the
136 class' own methods. In the example above, the constructor method is
137 the only overridden method: it is set to
138 <function>maman_bar_constructor</function>.
142 Once <function><link linkend="g-object-new">g_object_new</link></function> has obtained a reference to an initialized
143 class structure, it invokes its constructor method to create an instance of the new
144 object. Since it has just been overridden by <function>maman_bar_class_init</function>
145 to <function>maman_bar_constructor</function>, the latter is called and, because it
146 was implemented correctly, it chains up to its parent's constructor. In
147 order to find the parent class and chain up to the parent class
148 constructor, we can use the <literal>maman_bar_parent_class</literal>
149 pointer that has been set up for us by the
150 <literal>G_DEFINE_TYPE</literal> macro.
154 Finally, at one point or another, <function>g_object_constructor</function> is invoked
155 by the last constructor in the chain. This function allocates the object's instance' buffer
156 through <function><link linkend="g-type-create-instance">g_type_create_instance</link></function>
157 which means that the instance_init function is invoked at this point if one
158 was registered. After instance_init returns, the object is fully initialized and should be
159 ready to answer any user-request. When <function><link linkend="g-type-create-instance">g_type_create_instance</link></function>
160 returns, <function>g_object_constructor</function> sets the construction properties
161 (i.e. the properties which were given to <function><link linkend="g-object-new">g_object_new</link></function>) and returns
162 to the user's constructor which is then allowed to do useful instance initialization...
166 The process described above might seem a bit complicated, but it can be
167 summarized easily by the table below which lists the functions invoked
168 by <function><link linkend="g-object-new">g_object_new</link></function>
169 and their order of invocation:
173 <table id="gobject-construction-table">
174 <title><function><link linkend="g-object-new">g_object_new</link></function></title>
176 <colspec colwidth="*" colnum="1" align="left"/>
177 <colspec colwidth="*" colnum="2" align="left"/>
178 <colspec colwidth="8*" colnum="3" align="left"/>
182 <entry>Invocation time</entry>
183 <entry>Function Invoked</entry>
184 <entry>Function's parameters</entry>
185 <entry>Remark</entry>
190 <entry morerows="3">First call to <function><link linkend="g-object-new">g_object_new</link></function> for target type</entry>
191 <entry>target type's base_init function</entry>
192 <entry>On the inheritance tree of classes from fundamental type to target type.
193 base_init is invoked once for each class structure.</entry>
195 I have no real idea on how this can be used. If you have a good real-life
196 example of how a class' base_init can be used, please, let me know.
200 <!--entry>First call to <function><link linkend="g-object-new">g_object_new</link></function> for target type</entry-->
201 <entry>target type's class_init function</entry>
202 <entry>On target type's class structure</entry>
204 Here, you should make sure to initialize or override class methods (that is,
205 assign to each class' method its function pointer) and create the signals and
206 the properties associated to your object.
210 <!--entry>First call to <function><link linkend="g-object-new">g_object_new</link></function> for target type</entry-->
211 <entry>interface' base_init function</entry>
212 <entry>On interface' vtable</entry>
216 <!--entry>First call to <function><link linkend="g-object-new">g_object_new</link></function> for target type</entry-->
217 <entry>interface' interface_init function</entry>
218 <entry>On interface' vtable</entry>
222 <entry morerows="1">Each call to <function><link linkend="g-object-new">g_object_new</link></function> for target type</entry>
223 <entry>target type's class constructor method: GObjectClass->constructor</entry>
224 <entry>On object's instance</entry>
226 If you need to complete the object initialization after all the construction properties
227 are set, override the constructor method and make sure to chain up to the object's
228 parent class before doing your own initialization.
229 In doubt, do not override the constructor method.
233 <!--entry>Each call to <function><link linkend="g-object-new">g_object_new</link></function> for target type</entry-->
234 <entry>type's instance_init function</entry>
235 <entry>On the inheritance tree of classes from fundamental type to target type.
236 the instance_init provided for each type is invoked once for each instance
239 Provide an instance_init function to initialize your object before its construction
240 properties are set. This is the preferred way to initialize a GObject instance.
241 This function is equivalent to C++ constructors.
250 Readers should feel concerned about one little twist in the order in
251 which functions are invoked: while, technically, the class' constructor
252 method is called <emphasis>before</emphasis> the GType's instance_init
253 function (since <function><link linkend="g-type-create-instance">g_type_create_instance</link></function> which calls instance_init is called by
254 <function>g_object_constructor</function> which is the top-level class
255 constructor method and to which users are expected to chain to), the
256 user's code which runs in a user-provided constructor will always
257 run <emphasis>after</emphasis> GType's instance_init function since the
258 user-provided constructor <emphasis>must</emphasis> (you've been warned)
259 chain up <emphasis>before</emphasis> doing anything useful.
263 <sect1 id="gobject-memory">
264 <title>Object memory management</title>
267 The memory-management API for GObjects is a bit complicated but the idea behind it
268 is pretty simple: the goal is to provide a flexible model based on reference counting
269 which can be integrated in applications which use or require different memory management
270 models (such as garbage collection, aso...). The methods which are used to
271 manipulate this reference count are described below.
276 gpointer g_object_ref (gpointer object);
277 void g_object_unref (gpointer object);
282 typedef void (*GWeakNotify) (gpointer data,
283 GObject *where_the_object_was);
285 void g_object_weak_ref (GObject *object,
288 void g_object_weak_unref (GObject *object,
291 void g_object_add_weak_pointer (GObject *object,
292 gpointer *weak_pointer_location);
293 void g_object_remove_weak_pointer (GObject *object,
294 gpointer *weak_pointer_location);
298 void g_object_run_dispose (GObject *object);
302 <sect2 id="gobject-memory-refcount">
303 <title>Reference count</title>
306 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
307 increase and decrease the reference count.These functions are thread-safe as of GLib 2.8.
308 The reference count is, unsurprisingly, initialized to one by
309 <function><link linkend="g-object-new">g_object_new</link></function> which means that the caller
310 is currently the sole owner of the newly-created reference.
311 When the reference count reaches zero, that is,
312 when <function><link linkend="g-object-unref">g_object_unref</link></function> is called by the last client holding
313 a reference to the object, the <emphasis>dispose</emphasis> and the
314 <emphasis>finalize</emphasis> class methods are invoked.
317 Finally, after <emphasis>finalize</emphasis> is invoked,
318 <function><link linkend="g-type-free-instance">g_type_free_instance</link></function> is called to free the object instance.
319 Depending on the memory allocation policy decided when the type was registered (through
320 one of the <function>g_type_register_*</function> functions), the object's instance
321 memory will be freed or returned to the object pool for this type.
322 Once the object has been freed, if it was the last instance of the type, the type's class
323 will be destroyed as described in <xref linkend="gtype-instantiable-classed"/> and
324 <xref linkend="gtype-non-instantiable-classed"/>.
328 The table below summarizes the destruction process of a GObject:
329 <table id="gobject-destruction-table">
330 <title><function><link linkend="g-object-unref">g_object_unref</link></function></title>
332 <colspec colwidth="*" colnum="1" align="left"/>
333 <colspec colwidth="*" colnum="2" align="left"/>
334 <colspec colwidth="8*" colnum="3" align="left"/>
338 <entry>Invocation time</entry>
339 <entry>Function Invoked</entry>
340 <entry>Function's parameters</entry>
341 <entry>Remark</entry>
346 <entry morerows="1">Last call to <function><link linkend="g-object-unref">g_object_unref</link></function> for an instance
349 <entry>target type's dispose class function</entry>
350 <entry>GObject instance</entry>
352 When dispose ends, the object should not hold any reference to any other
353 member object. The object is also expected to be able to answer client
354 method invocations (with possibly an error code but no memory violation)
355 until finalize is executed. dispose can be executed more than once.
356 dispose should chain up to its parent implementation just before returning
361 <!--entry>Last call to <function><link linkend="g-object-unref">g_object_unref</link></function> for an instance
364 <entry>target type's finalize class function</entry>
365 <entry>GObject instance</entry>
367 Finalize is expected to complete the destruction process initiated by
368 dispose. It should complete the object's destruction. finalize will be
370 finalize should chain up to its parent implementation just before returning
372 The reason why the destruction process is split is two different phases is
373 explained in <xref linkend="gobject-memory-cycles"/>.
377 <entry morerows="3">Last call to <function><link linkend="g-object-unref">g_object_unref</link></function> for the last
378 instance of target type
380 <entry>interface' interface_finalize function</entry>
381 <entry>On interface' vtable</entry>
382 <entry>Never used in practice. Unlikely you will need it.</entry>
385 <!--entry>Last call to <function><link linkend="g-object-unref">g_object_unref</link></function>for the last
386 instance of target type
388 <entry>interface' base_finalize function</entry>
389 <entry>On interface' vtable</entry>
390 <entry>Never used in practice. Unlikely you will need it.</entry>
393 <!--entry>Last call to <function><link linkend="g-object-unref">g_object_unref</link></function> for the last
394 instance of target type
396 <entry>target type's class_finalize function</entry>
397 <entry>On target type's class structure</entry>
398 <entry>Never used in practice. Unlikely you will need it.</entry>
401 <!--entry>Last call to <function><link linkend="g-object-unref">g_object_unref</link></function> for the last
402 instance of target type
404 <entry>type's base_finalize function</entry>
405 <entry>On the inheritance tree of classes from fundamental type to target type.
406 base_init is invoked once for each class structure.</entry>
407 <entry>Never used in practice. Unlikely you will need it.</entry>
416 <sect2 id="gobject-memory-weakref">
417 <title>Weak References</title>
420 Weak References are used to monitor object finalization:
421 <function><link linkend="g-object-weak-ref">g_object_weak_ref</link></function> adds a monitoring callback which does
422 not hold a reference to the object but which is invoked when the object runs
423 its dispose method. As such, each weak ref can be invoked more than once upon
424 object finalization (since dispose can run more than once during object
429 <function><link linkend="g-object-weak-unref">g_object_weak_unref</link></function> can be used to remove a monitoring
430 callback from the object.
434 Weak References are also used to implement <function><link linkend="g-object-add-weak-pointer">g_object_add_weak_pointer</link></function>
435 and <function><link linkend="g-object-remove-weak-pointer">g_object_remove_weak_pointer</link></function>. These functions add a weak reference
436 to the object they are applied to which makes sure to nullify the pointer given by the user
437 when object is finalized.
442 <sect2 id="gobject-memory-cycles">
443 <title>Reference counts and cycles</title>
446 Note: the following section was inspired by James Henstridge. I guess this means that
447 all praise and all curses will be directly forwarded to him.
451 GObject's memory management model was designed to be easily integrated in existing code
452 using garbage collection. This is why the destruction process is split in two phases:
453 the first phase, executed in the dispose handler is supposed to release all references
454 to other member objects. The second phase, executed by the finalize handler is supposed
455 to complete the object's destruction process. Object methods should be able to run
456 without program error (that is, without segfault :) in-between the two phases.
460 This two-step destruction process is very useful to break reference counting cycles.
461 While the detection of the cycles is up to the external code, once the cycles have been
462 detected, the external code can invoke <function><link linkend="g-object-dispose">g_object_dispose</link></function> which
463 will indeed break any existing cycles since it will run the dispose handler associated
464 to the object and thus release all references to other objects.
468 Attentive readers might now have understood one of the rules about the dispose handler
469 we stated a bit sooner: the dispose handler can be invoked multiple times. Let's say we
470 have a reference count cycle: object A references B which itself references object A.
471 Let's say we have detected the cycle and we want to destroy the two objects. One way to
472 do this would be to invoke <function><link linkend="g-object-dispose">g_object_dispose</link></function> on one of the
477 If object A releases all its references to all objects, this means it releases its
478 reference to object B. If object B was not owned by anyone else, this is its last
479 reference count which means this last unref runs B's dispose handler which, in turn,
480 releases B's reference on object A. If this is A's last reference count, this last
481 unref runs A's dispose handler which is running for the second time before
482 A's finalize handler is invoked !
486 The above example, which might seem a bit contrived can really happen if your
487 GObject's are being handled by language bindings. I would thus suggest the rules stated above
488 for object destruction are closely followed. Otherwise, <emphasis>Bad Bad Things</emphasis>
494 <sect1 id="gobject-properties">
495 <title>Object properties</title>
498 One of GObject's nice features is its generic get/set mechanism for object
499 properties. When an object
500 is instantiated, the object's class_init handler should be used to register
501 the object's properties with <function><link linkend="g-object-class-install-property">g_object_class_install_property</link></function>
502 (implemented in <filename>gobject.c</filename>).
506 The best way to understand how object properties work is by looking at a real example
509 /************************************************/
511 /************************************************/
522 maman_bar_set_property (GObject *object,
527 MamanBar *self = MAMAN_BAR (object);
531 case PROP_MAMAN_NAME:
532 g_free (self->priv->name);
533 self->priv->name = g_value_dup_string (value);
534 g_print ("maman: %s\n", self->priv->name);
537 case PROP_PAPA_NUMBER:
538 self->priv->papa_number = g_value_get_uchar (value);
539 g_print ("papa: %u\n", self->priv->papa_number);
543 /* We don't have any other property... */
544 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
550 maman_bar_get_property (GObject *object,
555 MamanBar *self = MAMAN_BAR (object);
559 case PROP_MAMAN_NAME:
560 g_value_set_string (value, self->priv->name);
563 case PROP_PAPA_NUMBER:
564 g_value_set_uchar (value, self->priv->papa_number);
568 /* We don't have any other property... */
569 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
575 maman_bar_class_init (MamanBarClass *klass)
577 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 pspec = g_param_spec_string ("maman-name",
584 "Maman construct prop",
586 "no-name-set" /* default value */,
587 G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE);
588 g_object_class_install_property (gobject_class,
592 pspec = g_param_spec_uchar ("papa-number",
593 "Number of current Papa",
594 "Set/Get papa's number",
595 0 /* minimum value */,
596 10 /* maximum value */,
597 2 /* default value */,
599 g_object_class_install_property (gobject_class,
604 /************************************************/
606 /************************************************/
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);
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 calls
626 <function><link linkend="object-set-property">object_set_property</link></function> which first walks the class hierarchy,
627 from bottom, most derived type, to top, fundamental type to find the class
628 which registered that property. It then tries to convert the user-provided GValue
629 into a GValue whose type is that of the associated property.
633 If the user provides a signed char GValue, as is shown
634 here, and if the object's property was registered as an unsigned int,
635 <function><link linkend="g-value-transform">g_value_transform</link></function> will try to transform the input signed char into
636 an unsigned int. Of course, the success of the transformation depends on the availability
637 of the required transform function. In practice, there will almost always be a transformation
639 <para>Its behaviour might not be what you expect but it is up to you to actually avoid
640 relying on these transformations.
643 which matches and conversion will be carried out if needed.
647 After transformation, the <type><link linkend="GValue">GValue</link></type> is validated by
648 <function><link linkend="g-param-value-validate">g_param_value_validate</link></function> which makes sure the user's
649 data stored in the <type><link linkend="GValue">GValue</link></type> matches the characteristics specified by
650 the property's <type><link linkend="GParamSpec">GParamSpec</link></type>. Here, the <type><link linkend="GParamSpec">GParamSpec</link></type> 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 <type><link linkend="GParamSpec">GParamSpec</link></type>. 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 <type><link linkend="GParamSpec">GParamSpec</link></type> the <emphasis>param_id</emphasis>
666 It should be noted that the param_id used here need only to uniquely identify each
667 <type><link linkend="GParamSpec">GParamSpec</link></type> within the <type><link linkend="FooClass">FooClass</link></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 calls
680 <function><link linkend="g-object-notify-queue-thaw">g_object_notify_queue_thaw</link></function>. This function makes sure that
681 the "notify" signal is emitted on the object's instance with the changed property as
682 parameter unless notifications were frozen by <function><link linkend="g-object-freeze-notify">g_object_freeze_notify</link></function>.
686 <function><link linkend="g-object-thaw-notify">g_object_thaw_notify</link></function> can be used to re-enable notification of
687 property modifications through the "notify" signal. It is important to remember that
688 even if properties are changed while property change notification is frozen, the "notify"
689 signal will be emitted once for each of these changed properties as soon as the property
690 change notification is thawed: no property change is lost for the "notify" signal. Signal
691 can only be delayed by the notification freezing mechanism.
695 It sounds like a tedious task to set up GValues every time when one wants to modify a property.
696 In practice one will rarely do this. The functions <function><link linkend="g-object-set-property">g_object_set_property</link></function>
697 and <function><link linkend="g-object-get-property">g_object_get_property</link></function>
698 are meant to be used by language bindings. For application there is an easier way and
699 that is described next.
702 <sect2 id="gobject-multi-properties">
703 <title>Accessing multiple properties at once</title>
706 It is interesting to note that the <function><link linkend="g-object-set">g_object_set</link></function> and
707 <function><link linkend="g-object-set-valist">g_object_set_valist</link></function> (vararg version) functions can be used to set
708 multiple properties at once. The client code shown above can then be re-written as:
712 g_object_set (G_OBJECT (foo),
714 "maman-name", "test",
717 This saves us from managing the GValues that we were needing to handle when using
718 <function><link linkend="g-object-set-property">g_object_set_property</link></function>.
719 The code above will trigger one notify signal emission for each property modified.
723 Of course, the _get versions are also available: <function><link linkend="g-object-get">g_object_get</link></function>
724 and <function><link linkend="g-object-get-valist">g_object_get_valist</link></function> (vararg version) can be used to get numerous
729 These high level functions have one drawback - they don't provide a return result.
730 One should pay attention to the argument types and ranges when using them.
731 A known source of errors is to e.g. pass a gfloat instead of a gdouble and thus
732 shifting all subsequent parameters by four bytes. Also forgetting the terminating
733 NULL will lead to unexpected behaviour.
737 Really attentive readers now understand how <function><link linkend="g-object-new">g_object_new</link></function>,
738 <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>
739 work: they parse the user-provided variable number of parameters and invoke
740 <function><link linkend="g-object-set">g_object_set</link></function> on the parameters only after the object has been successfully constructed.
741 Of course, the "notify" signal will be emitted for each property set.
746 <!-- @todo tell here about how to pass use handle properties in derived classes -->