2 <title>How To ?</title>
5 This chapter tries to answer the real-life questions of users and presents
6 the most common scenario use-cases I could come up with.
7 The use-cases are presented from most likely to less likely.
14 <sect1 id="howto-gobject">
15 <title>How To define and implement a new GObject ?</title>
18 Clearly, this is one of the most common question people ask: they just want to crank code and
19 implement a subclass of a GObject. Sometimes because they want to create their own class hierarchy,
20 sometimes because they want to subclass one of GTK+'s widget. This chapter will focus on the
21 implementation of a subtype of GObject. The sample source code
22 associated to this section can be found in the documentation's source tarball, in the
23 <filename>sample/gobject</filename> directory:
25 <listitem><para><filename>maman-bar.{h|c}</filename>: this is the source for a object which derives from
26 <type>GObject</type> and which shows how to declare different types of methods on the object.
28 <listitem><para><filename>maman-subbar.{h|c}</filename>: this is the source for a object which derives from
29 <type>MamanBar</type> and which shows how to override some of its parent's methods.
31 <listitem><para><filename>maman-foo.{h|c}</filename>: this is the source for an object which derives from
32 <type>GObject</type> and which declares a signal.
34 <listitem><para><filename>test.c</filename>: this is the main source which instantiates an instance of
35 type and exercises their API.
40 <sect2 id="howto-gobject-header">
41 <title>Boilerplate header code</title>
44 The first step before writing the code for your GObject is to write the type's header which contains
45 the needed type, function and macro definitions. Each of these elements is nothing but a convention
46 which is followed not only by GTK+'s code but also by most users of GObject. If you feel the need
47 not to obey the rules stated below, think about it twice:
49 <listitem><para>If your users are a bit accustomed to GTK+ code or any Glib code, they will
50 be a bit surprised and getting used to the conventions you decided upon will take time (money) and
51 will make them grumpy (not a good thing)
54 You must assess the fact that these conventions might have been designed by both smart
55 and experienced people: maybe they were at least partly right. Try to put your ego aside.
61 Pick a name convention for your headers and source code and stick to it:
64 use a dash to separate the prefix from the typename: <filename>maman-bar.h</filename> and
65 <filename>maman-bar.c</filename> (this is the convention used by Nautilus and most Gnome libraries).
68 use an underscore to separate the prefix from the typename: <filename>maman_bar.h</filename> and
69 <filename>maman_bar.c</filename>.
72 Do not separate the prefix from the typename: <filename>mamanbar.h</filename> and
73 <filename>mamanbar.c</filename>. (this is the convention used by GTK+)
76 I personally like the first solution better: it makes reading file names easier for those with poor
81 The basic conventions for any header which exposes a GType are described in
82 <xref linkend="gtype-conventions"/>. Most GObject-based code also obeys onf of the following
83 conventions: pick one and stick to it.
86 If you want to declare a type named bar with prefix maman, name the type instance
87 <function>MamanBar</function> and its class <function>MamanBarClass</function>
88 (name is case-sensitive). It is customary to declare them with code similar to the
92 * Copyright/Licensing information.
99 * Potentially, include other headers on which this header depends.
107 typedef struct _MamanBar MamanBar;
108 typedef struct _MamanBarClass MamanBarClass;
112 /* instance members */
115 struct _MamanBarClass {
120 /* used by MAMAN_BAR_TYPE */
121 GType maman_bar_get_type (void);
124 * Method definitions.
131 Most GTK+ types declare their private fields in the public header with a /* private */ comment,
132 relying on their user's intelligence not to try to play with these fields. Fields not marked private
133 are considered public by default. The /* protected */ comment (same semantics as those of C++)
134 is also used, mainly in the GType library, in code written by Tim Janik.
145 All of Nautilus code and a lot of Gnome libraries use private indirection members, as described
146 by Herb Sutter in his Pimpl articles (see <ulink></ulink>: Herb summarizes the different
147 issues better than I will):
149 typedef struct _MamanBarPrivate MamanBarPrivate;
154 MamanBarPrivate *priv;
157 The private structure is then defined in the .c file, instantiated in the object's XXX
158 function and destroyed in the object's XXX function.
164 Finally, there are different header include conventions. Again, pick one and stick to it. I personally
165 use indifferently any of the two, depending on the codebase I work on: the rule is consistency.
168 Some people add at the top of their headers a number of #include directives to pull in
169 all the headers needed to compile client code. This allows client code to simply
170 #include "maman-bar.h".
173 Other do not #include anything and expect the client to #include themselves the headers
174 they need before including your header. This speeds up compilation because it minimizes the
175 amount of pre-processor work. This can be used in conjunction with the re-declaration of certain
176 unused types in the client code to minimize compile-time dependencies and thus speed up
184 <sect2 id="howto-gobject-code">
185 <title>Boilerplate code</title>
188 In your code, the first step is to #include the needed headers: depending on your header include strategy, this
189 can be as simple as #include "maman-bar.h" or as complicated as tens of #include lines ending with
190 #include "maman-bar.h":
193 * Copyright information
196 #include "maman-bar.h"
198 /* If you use Pimpls, include the private structure
199 * definition here. Some people create a maman-bar-private.h header
200 * which is included by the maman-bar.c file and which contains the
201 * definition for this private structure.
203 struct _MamanBarPrivate {
209 * forward definitions
215 Implement <function>maman_bar_get_type</function> and make sure the code compiles:
218 maman_bar_get_type (void)
220 static GType type = 0;
222 static const GTypeInfo info = {
223 sizeof (MamanBarClass),
224 NULL, /* base_init */
225 NULL, /* base_finalize */
226 NULL, /* class_init */
227 NULL, /* class_finalize */
228 NULL, /* class_data */
231 NULL /* instance_init */
233 type = g_type_register_static (G_TYPE_OBJECT,
243 <sect2 id="howto-gobject-construction">
244 <title>Object Construction</title>
247 People often get confused when trying to construct their GObjects because of the
248 sheer number of different ways to hook into the objects's construction process: it is
249 difficult to figure which is the <emphasis>correct</emphasis>, recommended way.
253 <xref linkend="gobject-construction-table"/> shows what user-provided functions
254 are invoked during object instanciation and in which order they are invoked.
255 A user looking for the equivalent of the simple C++ constructor function should use
256 the instance_init method. It will be invoked after all the parent's instance_init
257 functions have been invoked. It cannot take arbitrary construction parameters
258 (as in C++) but if your object needs arbitrary parameters to complete initialization,
259 you can use construction properties.
263 Construction properties will be set only after all instance_init functions have run.
264 No object reference will be returned to the client of <function>g_object_new></function>
265 until all the construction properties have been set.
269 As such, I would recommend writing the following code first:
272 maman_bar_init (GTypeInstance *instance,
275 MamanBar *self = (MamanBar *)instance;
276 self->private = g_new0 (MamanBarPrivate, 1);
278 /* initialize all public and private members to reasonable default values. */
279 /* If you need specific consruction properties to complete initialization,
280 * delay initialization completion until the property is set.
284 And make sure that you set <function>maman_bar_init</function> as the type's instance_init function
285 in <function>maman_bar_get_type</function>. Make sure the code builds and runs: create an instance
286 of the object and make sure <function>maman_bar_init</function> is called (add a
287 <function>g_print</function> call in it).
291 Now, if you need special construction properties, install the properties in the class_init function,
292 override the set and get methods and implement the get and set methods as described in
293 <xref linkend="gobject-properties"/>. Make sure that these properties use a construct only
294 pspec by setting the param spec's flag field to G_PARAM_CONSTRUCT_ONLY: this helps
295 GType ensure that these properties are not set again later by malicious user code.
298 bar_class_init (MamanBarClass *klass)
300 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
301 GParamSpec *maman_param_spec;
303 gobject_class->set_property = bar_set_property;
304 gobject_class->get_property = bar_get_property;
306 maman_param_spec = g_param_spec_string ("maman",
307 "Maman construct prop",
309 "no-name-set" /* default value */,
310 G_PARAM_CONSTRUCT_ONLY |G_PARAM_READWRITE);
312 g_object_class_install_property (gobject_class,
317 If you need this, make sure you can build and run code similar to the code shown above. Make sure
318 your construct properties can set correctly during construction, make sure you cannot set them
319 afterwards and make sure that if your users do not call <function>g_object_new</function>
320 with the required construction properties, these will be initialized with the default values.
324 I consider good taste to halt program execution if a construction property is set its
325 default value. This allows you to catch client code which does not give a reasonable
326 value to the construction properties. Of course, you are free to disagree but you
327 should have a good reason to do so.
330 <para>Some people sometimes need to construct their object but only after the construction properties
331 have been set. This is possible through the use of the constructor class method as described in
332 <xref linkend="gobject-instanciation"/>. However, I have yet to see <emphasis>any</emphasis> reasonable
333 use of this feature. As such, to initialize your object instances, use by default the base_init function
334 and construction properties.
338 <sect2 id="howto-gobject-destruction">
339 <title>Object Destruction</title>
342 Again, it is often difficult to figure out which mechanism to use to hook into the object's
343 destruction process: when the last <function>g_object_unref</function> function call is made,
344 a lot of things happen as described in <xref linkend="gobject-destruction-table"/>.
348 The destruction process of your object must be split is two different phases: you must override
349 both the dispose and the finalize class methods.
351 struct _MamanBarPrivate {
352 gboolean dispose_has_run;
356 bar_dispose (MamanBar *self)
358 if (self->private->dispose_has_run) {
359 /* If dispose did already run, return. */
362 /* Make sure dispose does not run twice. */
363 object->private->dispose_has_run = TRUE;
366 * In dispose, you are supposed to free all types referenced from this
367 * object which might themselves hold a reference to self. Generally,
368 * the most simple solution is to unref all members on which you own a
374 bar_finalize (MamanBar *self)
377 * Here, complete object destruction.
378 * You might not need to do much...
380 g_free (self->private);
384 bar_class_init (BarClass *klass)
386 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
388 gobject_class->dispose = bar_dispose;
389 gobject_class->finalize = bar_finalize;
393 maman_bar_init (GTypeInstance *instance,
396 MamanBar *self = (MamanBar *)instance;
397 self->private = g_new0 (MamanBarPrivate, 1);
398 self->private->dispose_has_run = FALSE;
404 Add similar code to your GObject, make sure the code still builds and runs: dispose and finalize must be called
405 during the last unref.
406 It is possible that object methods might be invoked after dispose is run and before finalize runs. GObject
407 does not consider this to be a program error: you must gracefully detect this and neither crash nor warn
408 the user. To do this, you need something like the following code at the start of each object method, to make
409 sure the object's data is still valid before manipulating it:
411 if (self->private->dispose_has_run) {
412 /* Dispose has run. Data is not valid anymore. */
419 <sect2 id="howto-gobject-methods">
420 <title>Object methods</title>
423 Just as with C++, there are many different ways to define object
424 methods and extend them: the following list and sections draw on C++ vocabulary.
425 (Readers are expected to know basic C++ buzzwords. Those who have not had to
426 write C++ code recently can refer to <ulink>XXXX</ulink> to refresh their
430 non-virtual public methods,
433 virtual public methods and
436 virtual private methods
442 <title>non-virtual public methods</title>
445 These are the simplest: you want to provide a simple method which can act on your object. All you need
446 to do is to provide a function prototype in the header and an implementation of that prototype
449 /* declaration in the header. */
450 void maman_bar_do_action (MamanBar *self, /* parameters */);
451 /* implementation in the source file */
452 void maman_bar_do_action (MamanBar *self, /* parameters */)
459 <para>There is really nothing scary about this.</para>
463 <title>Virtual Public methods</title>
466 This is the preferred way to create polymorphic GObjects. All you need to do is to
467 define the common method and its class function in the public header, implement the
468 common method in the source file and re-implement the class function in each object
469 which inherits from you.
471 /* declaration in maman-bar.h. */
472 struct _MamanBarClass {
476 void (*do_action) (MamanBar *self, /* parameters */);
478 void maman_bar_do_action (MamanBar *self, /* parameters */);
479 /* implementation in maman-bar.c */
480 void maman_bar_do_action (MamanBar *self, /* parameters */)
482 MAMAN_BAR_GET_CLASS (self)->do_action (self, /* parameters */);
485 The code above simply redirects the do_action call to the relevant class function. Some users,
486 concerned about performance, do not provide the <function>maman_bar_do_action</function>
487 wrapper function and require users to de-reference the class pointer themselves. This is not such
488 a great idea in terms of encapsulation and makes it difficult to change the object's implementation
489 afterwards, should this be needed.
493 Other users, also concerned by performance issues, declare the <function>maman_bar_do_action</function>
494 function inline in the header file. This, however, makes it difficult to change the
495 object's implementation later (although easier than requiring users to directly de-reference the class
496 function) and is often difficult to write in a portable way (the <emphasis>inline</emphasis> keyword
497 is not part of the C standard).
501 In doubt, unless a user shows you hard numbers about the performance cost of the function call,
502 just <function>maman_bar_do_action</function> in the source file.
506 Please, note that it is possible for you to provide a default implementation for this class method in
507 the object's class_init function: initialize the klass->do_action field to a pointer to the actual
508 implementation. You can also make this class method pure virtual by initializing the klass->do_action
512 maman_bar_real_do_action_two (MamanBar *self, /* parameters */)
514 /* Default implementation for the virtual method. */
518 maman_bar_class_init (BarClass *klass)
520 /* pure virtual method: mandates implementation in children. */
521 klass->do_action_one = NULL;
522 /* merely virtual method. */
523 klass->do_action_two = maman_bar_real_do_action_two;
526 void maman_bar_do_action_one (MamanBar *self, /* parameters */)
528 MAMAN_BAR_GET_CLASS (self)->do_action_one (self, /* parameters */);
530 void maman_bar_do_action_two (MamanBar *self, /* parameters */)
532 MAMAN_BAR_GET_CLASS (self)->do_action_two (self, /* parameters */);
539 <title>Virtual Private Methods</title>
542 These are very similar to Virtual Public methods. They just don't have a public function to call the
543 function directly. The header file contains only a declaration of the class function:
545 /* declaration in maman-bar.h. */
546 struct _MamanBarClass {
550 void (*helper_do_specific_action) (MamanBar *self, /* parameters */);
552 void maman_bar_do_any_action (MamanBar *self, /* parameters */);
554 These class functions are often used to delegate part of the job to child classes:
556 /* this accessor function is static: it is not exported outside of this file. */
558 maman_bar_do_specific_action (MamanBar *self, /* parameters */)
560 MAMAN_BAR_GET_CLASS (self)->do_specific_action (self, /* parameters */);
563 void maman_bar_do_any_action (MamanBar *self, /* parameters */)
565 /* random code here */
568 * Try to execute the requested action. Maybe the requested action cannot be implemented
569 * here. So, we delegate its implementation to the child class:
571 maman_bar_do_specific_action (self, /* parameters */);
573 /* other random code here */
579 Again, it is possible to provide a default implementation for this private virtual class function:
582 maman_bar_class_init (MamanBarClass *klass)
584 /* pure virtual method: mandates implementation in children. */
585 klass->do_specific_action_one = NULL;
586 /* merely virtual method. */
587 klass->do_specific_action_two = maman_bar_real_do_specific_action_two;
593 Children can then implement the subclass with code such as:
596 maman_bar_subtype_class_init (MamanBarSubTypeClass *klass)
598 MamanBarClass *bar_class = MAMAN_BAR_CLASS (klass);
599 /* implement pure virtual class function. */
600 bar_class->do_specific_action_one = maman_bar_subtype_do_specific_action_one;
606 Finally, it is interesting to note that, just like in C++, it is possible
607 to make each object class method chain to its parent class method:
610 maman_bar_real_do_action_two (MamanBar *self, /* parameters */)
612 MamanBarClass *bar_class = g_type_class_peek_parent (klass);
614 bar_class->do_action (self, /* parameters */);
616 /* do local stuff here. */
620 maman_bar_subtype_class_init (MamanBarSubTypeClass *klass)
622 MamanBarClass *bar_class = MAMAN_BAR_CLASS (klass);
623 /* implement pure virtual class function. */
624 bar_class->do_specific_action_one = maman_bar_subtype_do_specific_action_one;
643 <sect1 id="howto-interface">
644 <title>How To define and implement Interfaces ?</title>
646 <sect2 id="howto-interface-define">
647 <title>How To define Interfaces ?</title>
650 The bulk of interface definition has already been shown in <xref linkend="gtype-non-instantiable-classed"/>
651 but I feel it is needed to show exactly how to create an interface. The sample source code
652 associated to this section can be found in the documentation's source tarball, in the
653 <filename>sample/interface/maman-ibaz.{h|c}</filename> file.
657 As above, the first step is to get the header right:
662 #include <glib-object.h>
664 #define MAMAN_IBAZ_TYPE (maman_ibaz_get_type ())
665 #define MAMAN_IBAZ(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_IBAZ_TYPE, MamanIbaz))
666 #define MAMAN_IBAZ_CLASS(vtable) (G_TYPE_CHECK_CLASS_CAST ((vtable), MAMAN_IBAZ_TYPE, MamanIbazClass))
667 #define MAMAN_IS_IBAZ(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_IBAZ_TYPE))
668 #define MAMAN_IS_IBAZ_CLASS(vtable) (G_TYPE_CHECK_CLASS_TYPE ((vtable), MAMAN_IBAZ_TYPE))
669 #define MAMAN_IBAZ_GET_CLASS(inst) (G_TYPE_INSTANCE_GET_INTERFACE ((inst), MAMAN_IBAZ_TYPE, MamanIbazClass))
672 typedef struct _MamanIbaz MamanIbaz; /* dummy object */
673 typedef struct _MamanIbazClass MamanIbazClass;
675 struct _MamanIbazClass {
676 GTypeInterface parent;
678 void (*do_action) (MamanIbaz *self);
681 GType maman_ibaz_get_type (void);
683 void maman_ibaz_do_action (MamanIbaz *self);
685 #endif //MAMAN_IBAZ_H
687 This code is almost exactly similar to the code for a normal <type>GType</type>
688 which derives from a <type>GObject</type> except for a few details:
691 The <function>_GET_CLASS</function> macro is not implemented with
692 <function>G_TYPE_INSTANCE_GET_CLASS</function> but with <function>G_TYPE_INSTANCE_GET_INTERFACE</function>.
695 The instance type, <type>MamanIbaz</type> is not fully defined: it is used merely as an abstract
696 type which represents an instance of whatever object which implements the interface.
702 The implementation of the <type>MamanIbaz</type> type itself is trivial:
704 <listitem><para><function>maman_ibaz_get_type</function> registers the
705 type in the type system.
707 <listitem><para><function>maman_ibaz_base_init</function> is expected
708 to register the interface's signals if there are any (we will see a bit
709 (later how to use them). Make sure to use a static local boolean variable
710 to make sure not to run the initialization code twice (as described in
711 <xref linkend="gtype-non-instantiable-classed-init"/>,
712 <function>base_init</function> is run once for each interface implementation
713 instanciation)</para></listitem>
714 <listitem><para><function>maman_ibaz_do_action</function> de-references the class
715 structure to access its associated class function and calls it.
720 maman_ibaz_base_init (gpointer g_class)
722 static gboolean initialized = FALSE;
725 /* create interface signals here. */
731 maman_ibaz_get_type (void)
733 static GType type = 0;
735 static const GTypeInfo info = {
736 sizeof (MamanIbazClass),
737 maman_ibaz_base_init, /* base_init */
738 NULL, /* base_finalize */
739 NULL, /* class_init */
740 NULL, /* class_finalize */
741 NULL, /* class_data */
744 NULL /* instance_init */
746 type = g_type_register_static (G_TYPE_INTERFACE, "MamanIbaz", &info, 0);
751 void maman_ibaz_do_action (MamanIbaz *self)
753 MAMAN_IBAZ_GET_CLASS (self)->do_action (self);
759 <sect2 id="howto-interface-implement">
760 <title>How To define and implement an implementation of an Interface ?</title>
763 Once the interface is defined, implementing it is rather trivial. Source code showing how to do this
764 for the <type>IBaz</type> interface defined in the previous section is located in
765 <filename>sample/interface/maman-baz.{h|c}</filename>.
769 The first step is to define a normal GType. Here, we have decided to use a GType which derives from
770 GObject. Its name is <type>MamanBaz</type>:
775 #include <glib-object.h>
777 #define MAMAN_BAZ_TYPE (maman_baz_get_type ())
778 #define MAMAN_BAZ(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_BAZ_TYPE, Mamanbaz))
779 #define MAMAN_BAZ_CLASS(vtable) (G_TYPE_CHECK_CLASS_CAST ((vtable), MAMAN_BAZ_TYPE, MamanbazClass))
780 #define MAMAN_IS_BAZ(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_BAZ_TYPE))
781 #define MAMAN_IS_BAZ_CLASS(vtable) (G_TYPE_CHECK_CLASS_TYPE ((vtable), MAMAN_BAZ_TYPE))
782 #define MAMAN_BAZ_GET_CLASS(inst) (G_TYPE_INSTANCE_GET_CLASS ((inst), MAMAN_BAZ_TYPE, MamanbazClass))
785 typedef struct _MamanBaz MamanBaz;
786 typedef struct _MamanBazClass MamanBazClass;
793 struct _MamanBazClass {
797 GType maman_baz_get_type (void);
802 There is clearly nothing specifically weird or scary about this header: it does not define any weird API
803 or derives from a weird type.
807 The second step is to implement <function>maman_baz_get_type</function>:
810 maman_baz_get_type (void)
812 static GType type = 0;
814 static const GTypeInfo info = {
815 sizeof (MamanBazClass),
816 NULL, /* base_init */
817 NULL, /* base_finalize */
818 NULL, /* class_init */
819 NULL, /* class_finalize */
820 NULL, /* class_data */
823 baz_instance_init /* instance_init */
825 static const GInterfaceInfo ibaz_info = {
826 (GInterfaceInitFunc) baz_interface_init, /* interface_init */
827 NULL, /* interface_finalize */
828 NULL /* interface_data */
830 type = g_type_register_static (G_TYPE_OBJECT,
833 g_type_add_interface_static (type,
840 This function is very much like all the similar functions we looked at previously. The only interface-specific
841 code present here is the call to <function>g_type_add_interface_static</function> which is used to inform
842 the type system that this just-registered <type>GType</type> also implements the interface
843 <function>MAMAN_IBAZ_TYPE</function>.
847 <function>baz_interface_init</function>, the interface initialization function, is also pretty simple:
849 static void baz_do_action (MamanBaz *self)
851 g_print ("Baz implementation of IBaz interface Action: 0x%x.\n", self->instance_member);
854 baz_interface_init (gpointer g_iface,
857 MamanIbazClass *klass = (MamanIbazClass *)g_iface;
858 klass->do_action = (void (*) (MamanIbaz *self))baz_do_action;
861 baz_instance_init (GTypeInstance *instance,
864 MamanBaz *self = (MamanBaz *)instance;
865 self->instance_member = 0xdeadbeaf;
868 <function>baz_interface_init</function> merely initializes the interface methods to the implementations
869 defined by <type>MamanBaz</type>: <function>maman_baz_do_action</function> does nothing very useful
876 <title>Interface definition prerequisites</title>
880 <para>To specify that an interface requires the presence of other interfaces when implemented,
881 GObject introduces the concept of <emphasis>prerequisites</emphasis>: it is possible to associate
882 a list of prerequisite interfaces to an interface. For example, if object A wishes to implement interface
883 I1, and if interface I1 has a prerequisite on interface I2, A has to implement both I1 and I2.
886 <para>The mechanism described above is, in practice, very similar to Java's interface I1 extends
887 interface I2. The example below shows the GObject equivalent:
890 type = g_type_register_static (G_TYPE_INTERFACE, "MamanIbar", &info, 0);
891 /* Make the MamanIbar interface require MamanIbaz interface. */
892 g_type_interface_add_prerequisite (type, MAMAN_IBAZ_TYPE);
894 The code shown above adds the MamanIbaz interface to the list of prerequisites of MamanIbar while the
895 code below shows how an implementation can implement both interfaces and register their implementations:
897 static void ibar_do_another_action (MamanBar *self)
899 g_print ("Bar implementation of IBar interface Another Action: 0x%x.\n", self->instance_member);
903 ibar_interface_init (gpointer g_iface,
906 MamanIbarClass *klass = (MamanIbarClass *)g_iface;
907 klass->do_another_action = (void (*) (MamanIbar *self))ibar_do_another_action;
911 static void ibaz_do_action (MamanBar *self)
913 g_print ("Bar implementation of IBaz interface Action: 0x%x.\n", self->instance_member);
917 ibaz_interface_init (gpointer g_iface,
920 MamanIbazClass *klass = (MamanIbazClass *)g_iface;
921 klass->do_action = (void (*) (MamanIbaz *self))ibaz_do_action;
926 bar_instance_init (GTypeInstance *instance,
929 MamanBar *self = (MamanBar *)instance;
930 self->instance_member = 0x666;
935 maman_bar_get_type (void)
937 static GType type = 0;
939 static const GTypeInfo info = {
940 sizeof (MamanBarClass),
941 NULL, /* base_init */
942 NULL, /* base_finalize */
943 NULL, /* class_init */
944 NULL, /* class_finalize */
945 NULL, /* class_data */
948 bar_instance_init /* instance_init */
950 static const GInterfaceInfo ibar_info = {
951 (GInterfaceInitFunc) ibar_interface_init, /* interface_init */
952 NULL, /* interface_finalize */
953 NULL /* interface_data */
955 static const GInterfaceInfo ibaz_info = {
956 (GInterfaceInitFunc) ibaz_interface_init, /* interface_init */
957 NULL, /* interface_finalize */
958 NULL /* interface_data */
960 type = g_type_register_static (G_TYPE_OBJECT,
963 g_type_add_interface_static (type,
966 g_type_add_interface_static (type,
973 It is very important to notice that the order in which interface implementations are added to the main object
974 is not random: <function>g_type_interface_static</function> must be invoked first on the interfaces which have
975 no prerequisites and then on the others.
979 Complete source code showing how to define the MamanIbar interface which requires MamanIbaz and how to
980 implement the MamanIbar interface is located in <filename>sample/interface/maman-ibar.{h|c}</filename>
981 and <filename>sample/interface/maman-bar.{h|c}</filename>.
998 <sect1 id="howto-signals">
999 <title>Howto create and use signals</title>
1003 The signal system which was built in GType is pretty complex and flexible: it is possible for its users
1004 to connect at runtime any number of callbacks (implemented in any language for which a binding exists)
1006 <para>A python callback can be connected to any signal on any C-based GObject.
1010 to any signal and to stop the emission of any signal at any
1011 state of the signal emission process. This flexibility makes it possible to use GSignal for much more than
1012 just emit events which can be received by numerous clients.
1016 <title>Simple use of signals</title>
1018 <para>The most basic use of signals is to implement simple event notification: for example, if we have a
1019 MamanFile object, and if this object has a write method, we might wish to be notified whenever someone
1020 uses this method. The code below shows how the user can connect a callback to the write signal. Full code
1021 for this simple example is located in <filename>sample/signal/maman-file.{h|c}</filename> and
1022 in <filename>sample/signal/test.c</filename>
1024 file = g_object_new (MAMAN_FILE_TYPE, NULL);
1026 g_signal_connect (G_OBJECT (file), "write",
1027 (GCallback)write_event,
1030 maman_file_write (file, buffer, 50);
1035 The <type>MamanFile</type> signal is registered in the class_init function:
1037 klass->write_signal_id =
1038 g_signal_newv ("write",
1039 G_TYPE_FROM_CLASS (g_class),
1040 G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS,
1041 NULL /* class closure */,
1042 NULL /* accumulator */,
1043 NULL /* accu_data */,
1044 g_cclosure_marshal_VOID__VOID,
1045 G_TYPE_NONE /* return_type */,
1047 NULL /* param_types */);
1049 and the signal is emited in <function>maman_file_write</function>:
1051 void maman_file_write (MamanFile *self, guint8 *buffer, guint32 size)
1053 /* First write data. */
1054 /* Then, notify user of data written. */
1055 g_signal_emit (self, MAMAN_FILE_GET_CLASS (self)->write_signal_id,
1060 As shown above, you can safely set the details parameter to zero if you do not know what it can be used for.
1061 For a discussion of what you could used it for, see <xref linkend="signal-detail"/>
1071 <title>How to provide more flexibility to users ?</title>
1073 <para>The previous implementation does the job but the signal facility of GObject can be used to provide
1074 even more flexibility to this file change notification mechanism. One of the key ideas is to make the process
1075 of writing data to the file part of the signal emission process to allow users to be notified either
1076 before or after the data is written to the file.
1079 <para>To integrate the process of writing the data to the file into the signal emission mechanism, we can
1080 register a default class closure for this signal which will be invoked during the signal emission, just like
1081 any other user-connected signal handler.
1084 <para>The first step to implement this idea is to change the signature of the signal: we need to pass
1085 around the buffer to write and its size. To do this, we use our own marshaller which will be generated
1086 through glib's genmarshall tool. We thus create a file named <filename>marshall.list</filename> which contains
1087 the following single line:
1091 and use the Makefile provided in <filename>sample/signal/Makefile</filename> to generate the file named
1092 <filename>maman-file-complex-marshall.c</filename>. This C file is finally included in
1093 <filename>maman-file-complex.c</filename>.
1096 <para>Once the marshaller is present, we register the signal and its marshaller in the class_init function
1097 of the object <type>MamanFileComplex</type> (full source for this object is included in
1098 <filename>sample/signal/maman-file-complex.{h|c}</filename>):
1100 GClosure *default_closure;
1101 GType param_types[2];
1103 default_closure = g_cclosure_new (G_CALLBACK (default_write_signal_handler),
1104 (gpointer)0xdeadbeaf /* user_data */,
1105 NULL /* destroy_data */);
1107 param_types[0] = G_TYPE_POINTER;
1108 param_types[1] = G_TYPE_UINT;
1109 klass->write_signal_id =
1110 g_signal_newv ("write",
1111 G_TYPE_FROM_CLASS (g_class),
1112 G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS,
1113 default_closure /* class closure */,
1114 NULL /* accumulator */,
1115 NULL /* accu_data */,
1116 maman_file_complex_VOID__POINTER_UINT,
1117 G_TYPE_NONE /* return_type */,
1119 param_types /* param_types */);
1121 The code shown above first creates the closure which contains the code to complete the file write. This
1122 closure is registered as the default class_closure of the newly created signal.
1126 Of course, you need to implement completely the code for the default closure since I just provided
1130 default_write_signal_handler (GObject *obj, guint8 *buffer, guint size, gpointer user_data)
1132 g_assert (user_data == (gpointer)0xdeadbeaf);
1133 /* Here, we trigger the real file write. */
1134 g_print ("default signal handler: 0x%x %u\n", buffer, size);
1139 <para>Finally, the client code must invoke the <function>maman_file_complex_write</function> function which
1140 triggers the signal emission:
1142 void maman_file_complex_write (MamanFileComplex *self, guint8 *buffer, guint size)
1145 g_signal_emit (self,
1146 MAMAN_FILE_COMPLEX_GET_CLASS (self)->write_signal_id,
1153 <para>The client code (as shown in <filename>sample/signal/test.c</filename> and below) can now connect signal handlers before
1154 and after the file write is completed: since the default signal handler which does the write itself runs during the
1155 RUN_LAST phase of the signal emission, it will run after all handlers connected with <function>g_signal_connect</function>
1156 and before all handlers connected with <function>g_signal_connect_after</function>. If you intent to write a GObject
1157 which emits signals, I would thus urge you to create all your signals with the G_SIGNAL_RUN_LAST such that your users
1158 have a maximum of flexibility as to when to get the event. Here, we combined it with G_SIGNAL_NO_RECURSE and
1159 G_SIGNAL_NO_HOOKS to ensure our users will not try to do really weird things with our GObject. I strongly advise you
1160 to do the same unless you really know why (in which case you really know the inner workings of GSignal by heart and
1161 you are not reading this).
1166 static void complex_write_event_before (GObject *file, guint8 *buffer, guint size, gpointer user_data)
1168 g_assert (user_data == NULL);
1169 g_print ("Complex Write event before: 0x%x, %u\n", buffer, size);
1172 static void complex_write_event_after (GObject *file, guint8 *buffer, guint size, gpointer user_data)
1174 g_assert (user_data == NULL);
1175 g_print ("Complex Write event after: 0x%x, %u\n", buffer, size);
1178 static void test_file_complex (void)
1183 file = g_object_new (MAMAN_FILE_COMPLEX_TYPE, NULL);
1185 g_signal_connect (G_OBJECT (file), "write",
1186 (GCallback)complex_write_event_before,
1189 g_signal_connect_after (G_OBJECT (file), "write",
1190 (GCallback)complex_write_event_after,
1193 maman_file_complex_write (MAMAN_FILE_COMPLEX (file), buffer, 50);
1195 g_object_unref (G_OBJECT (file));
1198 The code above generates the following output on my machine:
1200 Complex Write event before: 0xbfffe280, 50
1201 default signal handler: 0xbfffe280 50
1202 Complex Write event after: 0xbfffe280, 50
1208 <title>How most people do the same thing with less code</title>
1210 <para>For many historic reasons related to how the ancestor of GObject used to work in GTK+ 1.x versions,
1211 there is a much <emphasis>simpler</emphasis>
1213 <para>I personally think that this method is horribly mind-twisting: it adds a new indirection
1214 which unecessarily complicates the overall code path. However, because this method is widely used
1215 by all of GTK+ and GObject code, readers need to understand it. The reason why this is done that way
1216 in most of GTK+ is related to the fact that the ancestor of GObject did not provide any other way to
1217 create a signal with a default handler than this one. Some people have tried to justify that it is done
1218 that way because it is better, faster (I am extremly doubtfull about the faster bit. As a matter of fact,
1219 the better bit also mystifies me ;-). I have the feeling no one really knows and everyone does it
1220 because they copy/pasted code from code which did the same. It is probably better to leave this
1221 specific trivia to hacker legends domain...
1224 way to create a signal with a default handler than to create
1225 a closure by hand and to use the <function>g_signal_newv</function>.
1228 <para>For example, <function>g_signal_new</function> can be used to create a signal which uses a default
1229 handler which is stored in the class structure of the object. More specifically, the class structure
1230 contains a function pointer which is accessed during signal emission to invoke the default handler and
1231 the user is expected to provide to <function>g_signal_new</function> the offset from the start of the
1232 class structure to the function pointer.
1234 <para>I would like to point out here that the reason why the default handler of a signal is named everywhere
1235 a class_closure is probably related to the fact that it used to be really a function pointer stored in
1236 the class structure.
1241 <para>The following code shows the declaration of the <type>MamanFileSimple</type> class structure which contains
1242 the <function>write</function> function pointer.
1244 struct _MamanFileSimpleClass {
1245 GObjectClass parent;
1247 guint write_signal_id;
1249 /* signal default handlers */
1250 void (*write) (MamanFileSimple *self, guint8 *buffer, guint size);
1253 The <function>write</function> function pointer is initialied in the class_init function of the object
1254 to <function>default_write_signal_handler</function>:
1257 maman_file_simple_class_init (gpointer g_class,
1258 gpointer g_class_data)
1260 GObjectClass *gobject_class = G_OBJECT_CLASS (g_class);
1261 MamanFileSimpleClass *klass = MAMAN_FILE_SIMPLE_CLASS (g_class);
1263 klass->write = default_write_signal_handler;
1265 Finally, the signal is created with <function>g_signal_new</function> in the same class_init function:
1267 klass->write_signal_id =
1268 g_signal_new ("write",
1269 G_TYPE_FROM_CLASS (g_class),
1270 G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS,
1271 G_STRUCT_OFFSET (MamanFileSimpleClass, write),
1272 NULL /* accumulator */,
1273 NULL /* accu_data */,
1274 maman_file_complex_VOID__POINTER_UINT,
1275 G_TYPE_NONE /* return_type */,
1280 Of note, here, is the 4th argument to the function: it is an integer calculated by the <function>G_STRUCT_OFFSET</function>
1281 macro which indicates the offset of the member <emphasis>write</emphasis> from the start of the
1282 <type>MamanFileSimpleClass</type> class structure.
1284 <para>GSignal uses this offset to create a special wrapper closure
1285 which first retrieves the target function pointer before calling it.
1291 While the complete code for this type of default handler looks less clutered as shown in
1292 <filename>sample/signal/maman-file-simple.{h|c}</filename>, it contains numerous subtleties.
1293 The main subtle point which everyone must be aware of is that the signature of the default
1294 handler created that way does not have a user_data argument:
1295 <function>default_write_signal_handler</function> is different in
1296 <filename>sample/signal/maman-file-complex.c</filename> and in
1297 <filename>sample/signal/maman-file-simple.c</filename>.
1300 <para>If you have doubts about which method to use, I would advise you to use the second one which
1301 involves <function>g_signal_new</function> rather than <function>g_signal_newv</function>:
1302 it is better to write code which looks like the vast majority of other GTK+/Gobject code than to
1303 do it your own way. However, now, you know why.
1314 <title>How users can abuse signals (and why some think it is good)</title>
1316 <para>Now that you know how to create signals to which the users can connect easily and at any point in
1317 the signal emission process thanks to <function>g_signal_connect</function>,
1318 <function>g_signal_connect_after</function> and G_SIGNAL_RUN_LAST, it is time to look into how your
1319 users can and will screw you. This is also interesting to know how you too, can screw other people.
1320 This will make you feel good and eleet.
1323 <para>The users can:
1325 <listitem><para>stop the emission of the signal at anytime</para></listitem>
1326 <listitem><para>override the default handler of the signal if it is stored as a function
1327 pointer in the class structure (which is the prefered way to create a default signal handler,
1328 as discussed in the previous section).</para></listitem>
1332 <para>In both cases, the original programmer should be as careful as possible to write code which is
1333 resistant to the fact that the default handler of the signal might not able to run. This is obviously
1334 not the case in the example used in the previous sections since the write to the file depends on whether
1335 or not the default handler runs (however, this might be your goal: to allow the user to prevent the file
1336 write if he wishes to).
1339 <para>If all you want to do is to stop the signal emission from one of the callbacks you connected yourself,
1340 you can call <function>g_signal_stop_by_name</function>. Its use is very simple which is why I won't detail
1344 <para>If the signal's default handler is just a class function pointer, it is also possible to override
1345 it yourself from the class_init function of a type which derives from the parent. That way, when the signal
1346 is emitted, the parent class will use the function provided by the child as a signal default handler.
1347 Of course, it is also possible (and recommended) to chain up from the child to the parent's default signal
1348 handler to ensure the integrity of the parent object.
1351 <para>Overriding a class method and chaining up was demonstrated in <xref linkend="howto-gobject-methods"/>
1352 which is why I won't bother to show exactly how to do it here again.</para>
1361 <title>Warning on signal creation and default closure</title>
1364 Most of the existing code I have seen up to now (in both GTK+, Gnome libraries and
1365 many GTK+ and Gnome applications) using signals uses a small
1366 variation of the default handler pattern I have shown in the previous section.
1370 Usually, the <function>g_signal_new</function> function is preferred over
1371 <function>g_signal_newv</function>. When <function>g_signal_new</function>
1372 is used, the default closure is exported as a class function. For example,
1373 <filename>gobject.h</filename> contains the declaration of <type>GObjectClass</type>
1374 whose notify class function is the default handler for the <emphasis>notify</emphasis>
1377 struct _GObjectClass
1379 GTypeClass g_type_class;
1381 /* class methods and other stuff. */
1384 void (*notify) (GObject *object,
1391 <filename>gobject.c</filename>'s <function>g_object_do_class_init</function> function
1392 registers the <emphasis>notify</emphasis> signal and initializes this class function
1396 g_object_do_class_init (GObjectClass *class)
1401 class->notify = NULL;
1403 gobject_signals[NOTIFY] =
1404 g_signal_new ("notify",
1405 G_TYPE_FROM_CLASS (class),
1406 G_SIGNAL_RUN_FIRST | G_SIGNAL_NO_RECURSE | G_SIGNAL_DETAILED | G_SIGNAL_NO_HOOKS,
1407 G_STRUCT_OFFSET (GObjectClass, notify),
1409 g_cclosure_marshal_VOID__PARAM,
1414 <function>g_signal_new</function> creates a <type>GClosure</type> which de-references the
1415 type's class structure to access the class function pointer and invoke it if it not NULL. The
1416 class function is ignored it is set to NULL.
1420 To understand the reason for such a complex scheme to access the signal's default handler,
1421 you must remember the whole reason for the use of these signals. The goal here is to delegate
1422 a part of the process to the user without requiring the user to subclass the object to override
1423 one of the class functions. The alternative to subclassing, that is, the use of signals
1424 to delegate processing to the user, is, however, a bit less optimal in terms of speed: rather
1425 than just de-referencing a function pointer in a class structure, you must start the whole
1426 process of signal emission which is a bit heavyweight.
1430 This is why some people decided to use class functions for some signal's default handlers:
1431 rather than having users connect a handler to the signal and stop the signal emission
1432 from within that handler, you just need to override the default class function which is
1433 supposedly more efficient.
1441 <sect1 id="howto-doc">
1442 <title>How to generate API documentation for your type ?</title>