1 <?xml version='1.0' encoding="ISO-8859-1"?>
2 <!DOCTYPE part PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN"
3 "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
6 <title>Tutorial</title>
9 This chapter tries to answer the real-life questions of users and presents
10 the most common scenario use cases I could come up with.
11 The use cases are presented from most likely to less likely.
15 <chapter id="howto-gobject">
16 <title>How to define and implement a new GObject</title>
19 Clearly, this is one of the most common questions people ask: they just
20 want to crank code and implement a subclass of a GObject. Sometimes because
21 they want to create their own class hierarchy, sometimes because they want
22 to subclass one of GTK+'s widget. This chapter will focus on the
23 implementation of a subtype of GObject.
26 <sect1 id="howto-gobject-header">
27 <title>Boilerplate header code</title>
30 The first step before writing the code for your GObject is to write the
31 type's header which contains the needed type, function and macro
32 definitions. Each of these elements is nothing but a convention which
33 is followed not only by GTK+'s code but also by most users of GObject.
34 If you feel the need not to obey the rules stated below, think about it
37 <listitem><para>If your users are a bit accustomed to GTK+ code or any
38 GLib code, they will be a bit surprised and getting used to the
39 conventions you decided upon will take time (money) and will make them
40 grumpy (not a good thing)</para></listitem>
41 <listitem><para>You must assess the fact that these conventions might
42 have been designed by both smart and experienced people: maybe they
43 were at least partly right. Try to put your ego aside.</para></listitem>
45 It is, nevertheless, important to note that these rules generally apply
46 to code that is meant to be called by third parties; it is perfectly
47 possible to write a valid, self-contained GObject types without most of
48 the boilerplate used in this tutorial; most of the boilerplate is also
49 not strictly required if you plan to use the GObject types only through
50 language bindings based on introspection.
54 Pick a name convention for your headers and source code and stick to it:
56 <listitem><para>use a dash to separate the prefix from the typename:
57 <filename>maman-bar.h</filename> and <filename>maman-bar.c</filename>
58 (this is the convention used by Nautilus and most GNOME libraries).</para></listitem>
59 <listitem><para>use an underscore to separate the prefix from the
60 typename: <filename>maman_bar.h</filename> and
61 <filename>maman_bar.c</filename>.</para></listitem>
62 <listitem><para>Do not separate the prefix from the typename:
63 <filename>mamanbar.h</filename> and <filename>mamanbar.c</filename>.
64 (this is the convention used by GTK+)</para></listitem>
66 Some people like the first two solutions better: it makes reading file
67 names easier for those with poor eyesight.
71 When you need some private (internal) declarations in several
72 (sub)classes, you can define them in a private header file which
73 is often named by appending the <emphasis>private</emphasis> keyword
74 to the public header name. For example, one could use
75 <filename>maman-bar-private.h</filename>,
76 <filename>maman_bar_private.h</filename> or
77 <filename>mamanbarprivate.h</filename>. Typically, such private header
78 files are not installed.
82 The basic conventions for any header which exposes a GType are described
83 in <xref linkend="gtype-conventions"/>. Most GObject-based code also
84 obeys one of of the following conventions: pick one and stick to it.
87 If you want to declare a type named bar with prefix maman, name the type instance
88 <function>MamanBar</function> and its class <function>MamanBarClass</function>
89 (name is case-sensitive). It is customary to declare them with code similar to the
93 * Copyright/Licensing information.
97 #ifndef __MAMAN_BAR_H__
98 #define __MAMAN_BAR_H__
100 #include <glib-object.h>
102 * Potentially, include other headers on which this header depends.
108 #define MAMAN_TYPE_BAR (maman_bar_get_type ())
109 #define MAMAN_BAR(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_TYPE_BAR, MamanBar))
110 #define MAMAN_IS_BAR(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_TYPE_BAR))
111 #define MAMAN_BAR_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), MAMAN_TYPE_BAR, MamanBarClass))
112 #define MAMAN_IS_BAR_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), MAMAN_TYPE_BAR))
113 #define MAMAN_BAR_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), MAMAN_TYPE_BAR, MamanBarClass))
115 typedef struct _MamanBar MamanBar;
116 typedef struct _MamanBarClass MamanBarClass;
120 /* Parent instance structure */
121 GObject parent_instance;
123 /* instance members */
126 struct _MamanBarClass
128 /* Parent class structure */
129 GObjectClass parent_class;
134 /* used by MAMAN_TYPE_BAR */
135 GType maman_bar_get_type (void);
138 * Method definitions.
141 #endif /* __MAMAN_BAR_H__ */
145 Types that require per-instance private data should use the
146 G_DEFINE_TYPE_WITH_PRIVATE() macro, or use the G_ADD_PRIVATE()
147 macro with the G_DEFINE_TYPE_WITH_CODE() or the G_DEFINE_TYPE_EXTENDED()
148 macros. The private structure is then defined in the .c file,
149 and can be accessed using the <function>get_instance_private()</function>
150 function generated by the G_DEFINE_TYPE_* macros.
152 struct _MamanBarPrivate
157 G_DEFINE_TYPE_WITH_PRIVATE (MamanBar, maman_bar, G_TYPE_OBJECT)
160 maman_bar_class_init (MamanBarClass *klass)
165 maman_bar_init (MamanBar *self)
167 /* maman_bar_get_instance_private() is generated by G_DEFINE_TYPE_WITH_PRIVATE()
168 * above, and it's local to the current compilation unit.
170 MamanBarPrivate *priv = maman_bar_get_instance_private (self);
178 Most GNOME libraries use a pointer inside the instance structure
179 for simpler access to the private data structure, as described by
180 Herb Sutter in his Pimpl article (see <ulink url="http://www.gotw.ca/gotw/024.htm">Compilation Firewalls</ulink>
181 and <ulink url="http://www.gotw.ca/gotw/028.htm">The Fast Pimpl Idiom</ulink>
182 for reference). If you opt to use this idiom, you can assign the
183 pointer inside the instance initialization function, e.g.:
185 G_DEFINE_TYPE_WITH_PRIVATE (MamanBar, maman_bar, G_TYPE_OBJECT)
187 struct _MamanBarPrivate
193 maman_bar_class_init (MamanBarClass *klass)
198 maman_bar_init (MamanBar *self)
200 self->priv = maman_bar_get_instance_private (self);
201 self->priv->hsize = 42;
209 Finally, there are different header include conventions. Again, pick one
210 and stick to it. I personally use indifferently any of the two, depending
211 on the codebase I work on: the rule, as always, is consistency.
214 Some people add at the top of their headers a number of #include
215 directives to pull in all the headers needed to compile client
216 code. This allows client code to simply #include "maman-bar.h".
219 Other do not #include anything and expect the client to #include
220 themselves the headers they need before including your header. This
221 speeds up compilation because it minimizes the amount of
222 pre-processor work. This can be used in conjunction with the
223 re-declaration of certain unused types in the client code to
224 minimize compile-time dependencies and thus speed up compilation.
231 <sect1 id="howto-gobject-code">
232 <title>Boilerplate code</title>
235 In your code, the first step is to #include the needed headers: depending
236 on your header include strategy, this can be as simple as
237 <literal>#include "maman-bar.h"</literal> or as complicated as tens
238 of #include lines ending with <literal>#include "maman-bar.h"</literal>:
241 * Copyright information
244 #include "maman-bar.h"
246 /* If you use Pimpls, include the private structure
247 * definition here. Some people create a maman-bar-private.h header
248 * which is included by the maman-bar.c file and which contains the
249 * definition for this private structure.
251 struct _MamanBarPrivate {
257 * forward definitions
263 Call the <function>G_DEFINE_TYPE</function> macro using the name
264 of the type, the prefix of the functions and the parent GType to
265 reduce the amount of boilerplate needed. This macro will:
268 <listitem><simpara>implement the <function>maman_bar_get_type</function>
269 function</simpara></listitem>
270 <listitem><simpara>define a parent class pointer accessible from
271 the whole .c file</simpara></listitem>
275 G_DEFINE_TYPE (MamanBar, maman_bar, G_TYPE_OBJECT)
280 It is also possible to use the
281 <function>G_DEFINE_TYPE_WITH_CODE</function> macro to control the
282 get_type function implementation - for instance, to add a call to
283 <function>G_IMPLEMENT_INTERFACE</function> macro which will
284 call the <function>g_type_implement_interface</function> function,
285 or call the <function>G_ADD_PRIVATE</function> macro will add an
286 instance private data structure.
290 <sect1 id="howto-gobject-construction">
291 <title>Object Construction</title>
294 People often get confused when trying to construct their GObjects because of the
295 sheer number of different ways to hook into the objects's construction process: it is
296 difficult to figure which is the <emphasis>correct</emphasis>, recommended way.
300 <xref linkend="gobject-construction-table"/> shows what user-provided functions
301 are invoked during object instantiation and in which order they are invoked.
302 A user looking for the equivalent of the simple C++ constructor function should use
303 the instance_init method. It will be invoked after all the parent's instance_init
304 functions have been invoked. It cannot take arbitrary construction parameters
305 (as in C++) but if your object needs arbitrary parameters to complete initialization,
306 you can use construction properties.
310 Construction properties will be set only after all instance_init functions have run.
311 No object reference will be returned to the client of <function><link linkend="g-object-new">g_object_new</link></function>
312 until all the construction properties have been set.
316 It is important to note that object construction cannot <emphasis>ever</emphasis>
317 fail. If you require a fallible GObject construction, you can use the
318 GInitable and GAsyncInitable interfaces provided by the GIO library
322 As such, I would recommend writing the following code first:
324 G_DEFINE_TYPE_WITH_PRIVATE (MamanBar, maman_bar, G_TYPE_OBJECT)
327 maman_bar_class_init (MamanBarClass *klass)
332 maman_bar_init (MamanBar *self)
334 self->priv = maman_bar_get_instance_private (self);
336 /* initialize all public and private members to reasonable default values. */
342 If you need special construction properties, install the properties in
343 the <function>class_init()</function> function, override the <function>set_property()</function>
344 and <function>get_property()</function> methods of the GObject class,
345 and implement them as described by <xref linkend="gobject-properties"/>.
346 <informalexample><programlisting>
355 /* Keep a pointer to the properties definition */
356 static GParamSpec *obj_properties[N_PROPERTIES] = { NULL, };
359 bar_class_init (MamanBarClass *klass)
361 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
363 gobject_class->set_property = bar_set_property;
364 gobject_class->get_property = bar_get_property;
366 obj_properties[PROP_MAMAN] =
367 g_param_spec_string ("maman",
368 "Maman construct prop",
370 "no-name-set" /* default value */,
371 G_PARAM_CONSTRUCT_ONLY |
373 G_PARAM_STATIC_STRINGS);
375 g_object_class_install_properties (gobject_class,
379 </programlisting></informalexample>
380 If you need this, make sure you can build and run code similar to the
381 code shown above. Also, make sure your construct properties can be set
382 without side effects during construction.
386 Some people sometimes need to complete the initialization of a instance
387 of a type only after the properties passed to the constructors have been
388 set. This is possible through the use of the <function>constructor()</function>
389 class method as described in <xref linkend="gobject-instantiation"/> or,
390 more simply, using the <function>constructed()</function> class method
391 available since GLib 2.12. Note that the <function>constructed()</function>
392 virtual function will only be invoked after the properties marked as
393 G_PARAM_CONSTRUCT_ONLY or G_PARAM_CONSTRUCT have been consumed, but
394 before the regular properties passed to <function>g_object_new()</function>
399 <sect1 id="howto-gobject-destruction">
400 <title>Object Destruction</title>
403 Again, it is often difficult to figure out which mechanism to use to
404 hook into the object's destruction process: when the last
405 <function><link linkend="g-object-unref">g_object_unref</link></function>
406 function call is made, a lot of things happen as described in
407 <xref linkend="gobject-destruction-table"/>.
411 The destruction process of your object might be split in two different
412 phases: dispose and the finalize. This split is necessary to handle
413 potential cycles due to the nature of the reference counting mechanism
414 used by GObject, as well as dealing with temporary vivification of
415 instances in case of signal emission during the destruction sequence.
417 struct _MamanBarPrivate
424 G_DEFINE_TYPE_WITH_PRIVATE (MamanBar, maman_bar, G_TYPE_OBJECT)
427 maman_bar_dispose (GObject *gobject)
429 MamanBar *self = MAMAN_BAR (gobject);
431 /* In dispose(), you are supposed to free all types referenced from this
432 * object which might themselves hold a reference to self. Generally,
433 * the most simple solution is to unref all members on which you own a
437 /* dispose() might be called multiple times, so we must guard against
438 * calling g_object_unref() on an invalid GObject by setting the member
439 * NULL; g_clear_object() does this for us, atomically.
441 g_clear_object (&self->priv->an_object);
443 /* Always chain up to the parent class; there is no need to check if
444 * the parent class implements the dispose() virtual function: it is
445 * always guaranteed to do so
447 G_OBJECT_CLASS (maman_bar_parent_class)->dispose (gobject);
451 maman_bar_finalize (GObject *gobject)
453 MamanBar *self = MAMAN_BAR (gobject);
455 g_free (self->priv->a_string);
457 /* Always chain up to the parent class; as with dispose(), finalize()
458 * is guaranteed to exist on the parent's class virtual function table
460 G_OBJECT_CLASS (maman_bar_parent_class)->finalize (gobject);
464 maman_bar_class_init (MamanBarClass *klass)
466 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
468 gobject_class->dispose = maman_bar_dispose;
469 gobject_class->finalize = maman_bar_finalize;
473 maman_bar_init (MamanBar *self);
475 self->priv = maman_bar_get_instance_private (self);
477 self->priv->an_object = g_object_new (MAMAN_TYPE_BAZ, NULL);
478 self->priv->a_string = g_strdup ("Maman");
484 It is possible that object methods might be invoked after dispose is
485 run and before finalize runs. GObject does not consider this to be a
486 program error: you must gracefully detect this and neither crash nor
487 warn the user, by having a disposed instance revert to an inhert state.
491 <sect1 id="howto-gobject-methods">
492 <title>Object methods</title>
495 Just as with C++, there are many different ways to define object
496 methods and extend them: the following list and sections draw on
497 C++ vocabulary. (Readers are expected to know basic C++ concepts.
498 Those who have not had to write C++ code recently can refer to e.g.
499 <ulink url="http://www.cplusplus.com/doc/tutorial/"/> to refresh
503 non-virtual public methods,
506 virtual public methods and
509 virtual private methods
515 <title>Non-virtual public methods</title>
518 These are the simplest: you want to provide a simple method which
519 can act on your object. All you need to do is to provide a function
520 prototype in the header and an implementation of that prototype
523 /* declaration in the header. */
524 void maman_bar_do_action (MamanBar *self, /* parameters */);
526 /* implementation in the source file */
528 maman_bar_do_action (MamanBar *self, /* parameters */)
530 g_return_if_fail (MAMAN_IS_BAR (self));
539 <title>Virtual public methods</title>
542 This is the preferred way to create polymorphic GObjects. All you
543 need to do is to define the common method and its class function in
544 the public header, implement the common method in the source file
545 and re-implement the class function in each object which inherits
548 /* declaration in maman-bar.h. */
549 struct _MamanBarClass
551 GObjectClass parent_class;
554 void (*do_action) (MamanBar *self, /* parameters */);
557 void maman_bar_do_action (MamanBar *self, /* parameters */);
559 /* implementation in maman-bar.c */
561 maman_bar_do_action (MamanBar *self, /* parameters */)
563 g_return_if_fail (MAMAN_IS_BAR (self));
565 MAMAN_BAR_GET_CLASS (self)->do_action (self, /* parameters */);
568 The code above simply redirects the do_action call to the relevant
573 Please, note that it is possible for you to provide a default
574 implementation for this class method in the object's
575 <function>class_init</function> function: initialize the
576 klass->do_action field to a pointer to the actual implementation.
577 By default, class method that are not inherited are initialized to
578 NULL, and thus are to be considered "pure virtual".
581 maman_bar_real_do_action_two (MamanBar *self, /* parameters */)
583 /* Default implementation for the virtual method. */
587 maman_bar_class_init (BarClass *klass)
589 /* this is not necessary, except for demonstration purposes.
591 * pure virtual method: mandates implementation in children.
593 klass->do_action_one = NULL;
595 /* merely virtual method. */
596 klass->do_action_two = maman_bar_real_do_action_two;
600 maman_bar_do_action_one (MamanBar *self, /* parameters */)
602 g_return_if_fail (MAMAN_IS_BAR (self));
604 /* if the method is purely virtual, then it is a good idea to
605 * check that it has been overridden before calling it, and,
606 * depending on the intent of the class, either ignore it silently
609 if (MAMAN_BAR_GET_CLASS (self)->do_action_one != NULL)
610 MAMAN_BAR_GET_CLASS (self)->do_action_one (self, /* parameters */);
612 g_warning ("Class '%s' does not override the mandatory "
613 "MamanBarClass.do_action_one() virtual function.",
614 G_OBJECT_TYPE_NAME (self));
618 maman_bar_do_action_two (MamanBar *self, /* parameters */)
620 g_return_if_fail (MAMAN_IS_BAR (self));
622 MAMAN_BAR_GET_CLASS (self)->do_action_two (self, /* parameters */);
629 <title>Virtual private Methods</title>
632 These are very similar to Virtual Public methods. They just don't
633 have a public function to call the function directly. The header
634 file contains only a declaration of the class function:
636 /* declaration in maman-bar.h. */
637 struct _MamanBarClass
642 void (* helper_do_specific_action) (MamanBar *self, /* parameters */);
645 void maman_bar_do_any_action (MamanBar *self, /* parameters */);
647 These class functions are often used to delegate part of the job
650 /* this accessor function is static: it is not exported outside of this file. */
652 maman_bar_do_specific_action (MamanBar *self, /* parameters */)
654 MAMAN_BAR_GET_CLASS (self)->do_specific_action (self, /* parameters */);
658 maman_bar_do_any_action (MamanBar *self, /* parameters */)
660 /* random code here */
663 * Try to execute the requested action. Maybe the requested action
664 * cannot be implemented here. So, we delegate its implementation
665 * to the child class:
667 maman_bar_do_specific_action (self, /* parameters */);
669 /* other random code here */
675 Again, it is possible to provide a default implementation for this
676 private virtual class function:
679 maman_bar_class_init (MamanBarClass *klass)
681 /* pure virtual method: mandates implementation in children. */
682 klass->do_specific_action_one = NULL;
684 /* merely virtual method. */
685 klass->do_specific_action_two = maman_bar_real_do_specific_action_two;
691 Children can then implement the subclass with code such as:
694 maman_bar_subtype_class_init (MamanBarSubTypeClass *klass)
696 MamanBarClass *bar_class = MAMAN_BAR_CLASS (klass);
698 /* implement pure virtual class function. */
699 bar_class->do_specific_action_one = maman_bar_subtype_do_specific_action_one;
706 <sect1 id="howto-gobject-chainup">
707 <title>Chaining up</title>
709 <para>Chaining up is often loosely defined by the following set of
712 <listitem><para>Parent class A defines a public virtual method named <function>foo</function> and
713 provides a default implementation.</para></listitem>
714 <listitem><para>Child class B re-implements method <function>foo</function>.</para></listitem>
715 <listitem><para>In the method B::foo, the child class B calls its parent class method A::foo.</para></listitem>
717 There are various uses to this idiom:
719 <listitem><para>You need to extend the behaviour of a class without modifying its code. You create
720 a subclass to inherit its implementation, re-implement a public virtual method to modify the behaviour
721 and chain up to ensure that the previous behaviour is not really modified, just extended.
723 <listitem><para>You need to implement the Chain Of Responsibility pattern: each object of the inheritance
724 tree chains up to its parent (typically, at the beginning or the end of the method) to ensure that
725 they each handler is run in turn.</para></listitem>
730 To explicitly chain up to the implementation of the virtual method in the parent class,
731 you first need a handle to the original parent class structure. This pointer can then be used to
732 access the original class function pointer and invoke it directly.
735 The <emphasis>original</emphasis> adjective used in this sentence is not innocuous. To fully
736 understand its meaning, you need to recall how class structures are initialized: for each object type,
737 the class structure associated to this object is created by first copying the class structure of its
738 parent type (a simple <function>memcpy</function>) and then by invoking the class_init callback on
739 the resulting class structure. Since the class_init callback is responsible for overwriting the class structure
740 with the user re-implementations of the class methods, we cannot merely use the modified copy of the parent class
741 structure stored in our derived instance. We want to get a copy of the class structure of an instance of the parent
747 <para>The function <function><link linkend="g-type-class-peek-parent">g_type_class_peek_parent</link></function>
748 is used to access the original parent class structure. Its input is a
749 pointer to the class of the derived object and it returns a pointer to
750 the original parent class structure. Instead of using this function
751 directly, though, you should use the <function>parent_class</function>
752 pointer created and initialized for us by the G_DEFINE_TYPE_* family of
753 macros, for instance:
756 b_method_to_call (B *obj, int a)
758 /* do stuff before chain up */
760 /* call the method_to_call() virtual function on the
761 * parent of BClass, AClass.
763 * remember the explicit cast to AClass*
765 A_CLASS (b_parent_class)->method_to_call (obj, a);
767 /* do stuff after chain up */
775 <!-- End Howto GObject -->
777 <chapter id="howto-interface">
778 <title>How to define and implement interfaces</title>
780 <sect1 id="howto-interface-define">
781 <title>Defining interfaces</title>
784 The bulk of interface definition has already been shown in <xref linkend="gtype-non-instantiable-classed"/>
785 but I feel it is needed to show exactly how to create an interface.
789 As above, the first step is to get the header right. This interface
792 #ifndef __MAMAN_IBAZ_H__
793 #define __MAMAN_IBAZ_H__
795 #include <glib-object.h>
797 #define MAMAN_TYPE_IBAZ (maman_ibaz_get_type ())
798 #define MAMAN_IBAZ(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_TYPE_IBAZ, MamanIbaz))
799 #define MAMAN_IS_IBAZ(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_TYPE_IBAZ))
800 #define MAMAN_IBAZ_GET_INTERFACE(inst) (G_TYPE_INSTANCE_GET_INTERFACE ((inst), MAMAN_TYPE_IBAZ, MamanIbazInterface))
803 typedef struct _MamanIbaz MamanIbaz; /* dummy object */
804 typedef struct _MamanIbazInterface MamanIbazInterface;
806 struct _MamanIbazInterface
808 GTypeInterface parent_iface;
810 void (*do_action) (MamanIbaz *self);
811 void (*do_something) (MamanIbaz *self);
814 GType maman_ibaz_get_type (void);
816 void maman_ibaz_do_action (MamanIbaz *self);
817 void maman_ibaz_do_something (MamanIbaz *self);
819 #endif /* __MAMAN_IBAZ_H__ */
821 This code is the same as the code for a normal <link linkend="GType"><type>GType</type></link>
822 which derives from a <link linkend="GObject"><type>GObject</type></link> except for a few details:
825 The <function>_GET_CLASS</function> macro is called <function>_GET_INTERFACE</function>
826 and not implemented with <function><link linkend="G-TYPE-INSTANCE-GET-CLASS:CAPS">G_TYPE_INSTANCE_GET_CLASS</link></function>
827 but with <function><link linkend="G-TYPE-INSTANCE-GET-INTERFACE:CAPS">G_TYPE_INSTANCE_GET_INTERFACE</link></function>.
830 The instance type, <type>MamanIbaz</type> is not fully defined: it is
831 used merely as an abstract type which represents an instance of
832 whatever object which implements the interface.
835 The parent of the <type>MamanIbazInterface</type> is not
836 <type>GObjectClass</type> but <type>GTypeInterface</type>.
842 The implementation of the <type>MamanIbaz</type> type itself is trivial:
844 <listitem><para><function><link linkend="G-DEFINE-INTERFACE:CAPS">G_DEFINE_INTERFACE</link></function>
845 creates a <function>maman_ibaz_get_type</function> function which registers the
846 type in the type system. The third argument is used to define a
847 <link linkend="howto-interface-prerequisite">prerequisite interface</link>
848 (which we'll talk about more later). Just pass <code>0</code> for this
849 argument when an interface has no prerequisite.
851 <listitem><para><function>maman_ibaz_default_init</function> is expected
852 to register the interface's signals if there are any (we will see a bit
853 later how to use them).</para></listitem>
854 <listitem><para>The interface methods <function>maman_ibaz_do_action</function>
855 and <function>maman_ibaz_do_something</function> dereference the interface
856 structure to access its associated interface function and call it.
860 G_DEFINE_INTERFACE (MamanIbaz, maman_ibaz, 0);
863 maman_ibaz_default_init (gpointer g_class)
865 /* add properties and signals to the interface here */
869 maman_ibaz_do_action (MamanIbaz *self)
871 g_return_if_fail (MAMAN_IS_IBAZ (self));
873 MAMAN_IBAZ_GET_INTERFACE (self)->do_action (self);
877 maman_ibaz_do_something (MamanIbaz *self)
879 g_return_if_fail (MAMAN_IS_IBAZ (self));
881 MAMAN_IBAZ_GET_INTERFACE (self)->do_something (self);
887 <sect1 id="howto-interface-implement">
888 <title>Implementing interfaces</title>
891 Once the interface is defined, implementing it is rather trivial.
895 The first step is to define a normal GObject class, like:
897 #ifndef __MAMAN_BAZ_H__
898 #define __MAMAN_BAZ_H__
900 #include <glib-object.h>
902 #define MAMAN_TYPE_BAZ (maman_baz_get_type ())
903 #define MAMAN_BAZ(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_TYPE_BAZ, Mamanbaz))
904 #define MAMAN_IS_BAZ(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_TYPE_BAZ))
905 #define MAMAN_BAZ_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), MAMAN_TYPE_BAZ, MamanbazClass))
906 #define MAMAN_IS_BAZ_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), MAMAN_TYPE_BAZ))
907 #define MAMAN_BAZ_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), MAMAN_TYPE_BAZ, MamanbazClass))
910 typedef struct _MamanBaz MamanBaz;
911 typedef struct _MamanBazClass MamanBazClass;
915 GObject parent_instance;
917 gint instance_member;
920 struct _MamanBazClass
922 GObjectClass parent_class;
925 GType maman_baz_get_type (void);
927 #endif /* __MAMAN_BAZ_H__ */
929 <!-- Ha ha! "nothing weird or scary". I actually laughed out loud. Oh boy.
930 The fact that we're so intimate with GObject that all this doesn't look
931 wierd, that's the scary thing. :) -->
932 There is clearly nothing specifically weird or scary about this header:
933 it does not define any weird API or derive from a weird type.
937 The second step is to implement <type>MamanBaz</type> by defining
938 its GType. Instead of using
939 <function><link linkend="G-DEFINE-TYPE:CAPS">G_DEFINE_TYPE</link></function>
941 <function><link linkend="G-DEFINE-TYPE-WITH-CODE:CAPS">G_DEFINE_TYPE_WITH_CODE</link></function>
943 <function><link linkend="G-IMPLEMENT-INTERFACE:CAPS">G_IMPLEMENT_INTERFACE</link></function>
946 static void maman_ibaz_interface_init (MamanIbazInterface *iface);
948 G_DEFINE_TYPE_WITH_CODE (MamanBar, maman_bar, G_TYPE_OBJECT,
949 G_IMPLEMENT_INTERFACE (MAMAN_TYPE_IBAZ,
950 maman_ibaz_interface_init))
952 This definition is very much like all the similar functions we looked
953 at previously. The only interface-specific code present here is the call to
954 <function><link linkend="G-IMPLEMENT-INTERFACE:CAPS">G_IMPLEMENT_INTERFACE</link></function>.
957 <note><para>Classes can implement multiple interfaces by using multiple calls to
958 <function><link linkend="G-IMPLEMENT-INTERFACE:CAPS">G_IMPLEMENT_INTERFACE</link></function>
960 <function><link linkend="G-DEFINE-TYPE-WITH-CODE:CAPS">G_DEFINE_TYPE_WITH_CODE</link></function>
964 <function>maman_baz_interface_init</function>, the interface
965 initialization function: inside it every virtual method of the interface
966 must be assigned to its implementation:
969 maman_baz_do_action (MamanBaz *self)
971 g_print ("Baz implementation of Ibaz interface Action: 0x%x.\n",
972 self->instance_member);
976 maman_baz_do_something (MamanBaz *self)
978 g_print ("Baz implementation of Ibaz interface Something: 0x%x.\n",
979 self->instance_member);
983 maman_ibaz_interface_init (MamanIbazInterface *iface)
985 iface->do_action = maman_baz_do_action;
986 iface->do_something = maman_baz_do_something;
990 maman_baz_init (MamanBaz *self)
992 MamanBaz *self = MAMAN_BAZ (instance);
993 self->instance_member = 0xdeadbeaf;
999 <sect1 id="howto-interface-prerequisite">
1000 <title>Interface definition prerequisites</title>
1003 To specify that an interface requires the presence of other interfaces
1004 when implemented, GObject introduces the concept of
1005 <emphasis>prerequisites</emphasis>: it is possible to associate
1006 a list of prerequisite types to an interface. For example, if
1007 object A wishes to implement interface I1, and if interface I1 has a
1008 prerequisite on interface I2, A has to implement both I1 and I2.
1012 The mechanism described above is, in practice, very similar to
1013 Java's interface I1 extends interface I2. The example below shows
1014 the GObject equivalent:
1016 /* Make the MamanIbar interface require MamanIbaz interface. */
1017 G_DEFINE_INTERFACE (MamanIbar, maman_ibar, MAMAN_TYPE_IBAZ);
1019 In the <function><link linkend="G-DEFINE-INTERFACE:CAPS">G_DEFINE_INTERFACE</link></function>
1020 call above, the third parameter defines the prerequisite type. This
1021 is the GType of either an interface or a class. In this case
1022 the MamanIbaz interface is a prerequisite of the MamanIbar. The code
1023 below shows how an implementation can implement both interfaces and
1024 register their implementations:
1027 maman_ibar_do_another_action (MamanIbar *ibar)
1029 MamanBar *self = MAMAN_BAR (ibar);
1031 g_print ("Bar implementation of IBar interface Another Action: 0x%x.\n",
1032 self->instance_member);
1036 maman_ibar_interface_init (MamanIbarInterface *iface)
1038 iface->do_another_action = maman_ibar_do_another_action;
1042 maman_ibaz_do_action (MamanIbaz *ibaz)
1044 MamanBar *self = MAMAN_BAR (ibaz);
1046 g_print ("Bar implementation of Ibaz interface Action: 0x%x.\n",
1047 self->instance_member);
1051 maman_ibaz_do_something (MamanIbaz *ibaz)
1053 MamanBar *self = MAMAN_BAR (ibaz);
1055 g_print ("Bar implementation of Ibaz interface Something: 0x%x.\n",
1056 self->instance_member);
1060 maman_ibaz_interface_init (MamanIbazInterface *iface)
1062 iface->do_action = maman_ibaz_do_action;
1063 iface->do_something = maman_ibaz_do_something;
1067 maman_bar_class_init (MamanBarClass *klass)
1073 maman_bar_init (MamanBar *self)
1075 self->instance_member = 0x666;
1078 G_DEFINE_TYPE_WITH_CODE (MamanBar, maman_bar, G_TYPE_OBJECT,
1079 G_IMPLEMENT_INTERFACE (MAMAN_TYPE_IBAZ,
1080 maman_ibaz_interface_init)
1081 G_IMPLEMENT_INTERFACE (MAMAN_TYPE_IBAR,
1082 maman_ibar_interface_init))
1084 It is very important to notice that the order in which interface
1085 implementations are added to the main object is not random:
1086 <function><link linkend="g-type-add-interface-static">g_type_add_interface_static</link></function>,
1088 <function><link linkend="G-DEFINE-INTERFACE:CAPS">G_IMPLEMENT_INTERFACE</link></function>,
1089 must be invoked first on the interfaces which have no prerequisites and then on
1094 <sect1 id="howto-interface-properties">
1095 <title>Interface properties</title>
1098 GObject interfaces can also have
1099 properties. Declaration of the interface properties is similar to
1100 declaring the properties of ordinary GObject types as explained in
1101 <xref linkend="gobject-properties"/>, except that
1102 <function><link linkend="g-object-interface-install-property">g_object_interface_install_property</link></function>
1103 is used to declare the properties instead of
1104 <function><link linkend="g-object-class-install-property">g_object_class_install_property</link></function>.
1108 To include a property named 'name' of type <type>string</type> in the
1109 <type>maman_ibaz</type> interface example code above, we only need to
1113 That really is one line extended to six for the sake of clarity
1116 line in the <function>maman_ibaz_default_init</function> as shown below:
1119 maman_ibaz_default_init (gpointer g_iface)
1121 g_object_interface_install_property (g_iface,
1122 g_param_spec_string ("name",
1124 "Name of the MamanIbaz",
1126 G_PARAM_READWRITE));
1132 One point worth noting is that the declared property wasn't assigned an
1133 integer ID. The reason being that integer IDs of properties are used
1134 only inside the get and set methods and since interfaces do not
1135 implement properties, there is no need to assign integer IDs to
1136 interface properties.
1140 An implementation declares and defines it's properties in the usual
1141 way as explained in <xref linkend="gobject-properties"/>, except for one
1142 small change: it can declare the properties of the interface it
1143 implements using <function><link linkend="g-object-class-override-property">g_object_class_override_property</link></function>
1144 instead of <function><link linkend="g-object-class-install-property">g_object_class_install_property</link></function>.
1145 The following code snippet shows the modifications needed in the
1146 <type>MamanBaz</type> declaration and implementation above:
1151 GObject parent_instance;
1153 gint instance_member;
1164 maman_baz_set_property (GObject *object,
1166 const GValue *value,
1169 MamanBaz *baz = MAMAN_BAZ (object);
1175 baz->name = g_value_dup_string (value);
1179 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1185 maman_baz_get_property (GObject *object,
1190 MamanBaz *baz = MAMAN_BAZ (object);
1195 g_value_set_string (value, baz->name);
1199 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1205 maman_baz_class_init (MamanBazClass *klass)
1207 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1209 gobject_class->set_property = maman_baz_set_property;
1210 gobject_class->get_property = maman_baz_get_property;
1212 g_object_class_override_property (gobject_class, PROP_NAME, "name");
1220 <sect1 id="howto-interface-override">
1221 <title>Overriding interface methods</title>
1224 If a base class already implements an interface, and in a derived
1225 class you wish to implement the same interface overriding only certain
1226 methods of that interface, you just reimplement the interface and
1227 set only the interface methods you wish to override.
1231 In this example MamanDerivedBaz is derived from MamanBaz. Both
1232 implement the MamanIbaz interface. MamanDerivedBaz only implements one
1233 method of the MamanIbaz interface and uses the base class implementation
1237 maman_derived_ibaz_do_action (MamanIbaz *ibaz)
1239 MamanDerivedBaz *self = MAMAN_DERIVED_BAZ (ibaz);
1240 g_print ("DerivedBaz implementation of Ibaz interface Action\n");
1244 maman_derived_ibaz_interface_init (MamanIbazInterface *iface)
1246 /* Override the implementation of do_action */
1247 iface->do_action = maman_derived_ibaz_do_action;
1250 * We simply leave iface->do_something alone, it is already set to the
1251 * base class implementation.
1255 G_DEFINE_TYPE_WITH_CODE (MamanDerivedBaz, maman_derived_baz, MAMAN_TYPE_BAZ,
1256 G_IMPLEMENT_INTERFACE (MAMAN_TYPE_IBAZ,
1257 maman_derived_ibaz_interface_init)
1260 maman_derived_baz_class_init (MamanDerivedBazClass *klass)
1266 maman_derived_baz_init (MamanDerivedBaz *self)
1274 To access the base class interface implementation use
1275 <function><link linkend="g-type-interface-peek-parent">g_type_interface_peek_parent</link></function>
1276 from within an interface's <function>default_init</function> function.
1280 If you wish to call the base class implementation of an interface
1281 method from an derived class where than interface method has been
1282 overridden then you can stash away the pointer returned from
1283 <function><link linkend="g-type-interface-peek-parent">g_type_interface_peek_parent</link></function>
1284 in a global variable.
1288 In this example MamanDerivedBaz overides the
1289 <function>do_action</function> interface method. In it's overridden method
1290 it calls the base class implementation of the same interface method.
1292 static MamanIbazInterface *maman_ibaz_parent_interface = NULL;
1295 maman_derived_ibaz_do_action (MamanIbaz *ibaz)
1297 MamanDerivedBaz *self = MAMAN_DERIVED_BAZ (ibaz);
1298 g_print ("DerivedBaz implementation of Ibaz interface Action\n");
1300 /* Now we call the base implementation */
1301 maman_ibaz_parent_interface->do_action (ibaz);
1305 maman_derived_ibaz_interface_init (MamanIbazInterface *iface)
1307 maman_ibaz_parent_interface = g_type_interface_peek_parent (iface);
1308 iface->do_action = maman_derived_ibaz_do_action;
1311 G_DEFINE_TYPE_WITH_CODE (MamanDerivedBaz, maman_derived_baz, MAMAN_TYPE_BAZ,
1312 G_IMPLEMENT_INTERFACE (MAMAN_TYPE_IBAZ,
1313 maman_derived_ibaz_interface_init))
1316 maman_derived_baz_class_init (MamanDerivedBazClass *klass)
1321 maman_derived_baz_init (MamanDerivedBaz *self)
1330 <!-- End Howto Interfaces -->
1332 <chapter id="howto-signals">
1333 <title>How to create and use signals</title>
1336 The signal system which was built in GType is pretty complex and
1337 flexible: it is possible for its users to connect at runtime any
1338 number of callbacks (implemented in any language for which a binding
1341 <para>A Python callback can be connected to any signal on any
1342 C-based GObject, and vice versa, assuming that the Python object
1343 inherits from GObject.</para>
1345 to any signal and to stop the emission of any signal at any
1346 state of the signal emission process. This flexibility makes it
1347 possible to use GSignal for much more than just emit signals which
1348 can be received by numerous clients.
1351 <sect1 id="howto-simple-signals">
1352 <title>Simple use of signals</title>
1355 The most basic use of signals is to implement simple event
1356 notification: for example, if we have a MamanFile object, and
1357 if this object has a write method, we might wish to be notified
1358 whenever someone has changed something via our MamanFile instance.
1359 The code below shows how the user can connect a callback to the
1362 file = g_object_new (MAMAN_FILE_TYPE, NULL);
1364 g_signal_connect (file, "changed", G_CALLBACK (changed_event), NULL);
1366 maman_file_write (file, buffer, strlen (buffer));
1371 The <type>MamanFile</type> signal is registered in the class_init
1374 file_signals[CHANGED] =
1375 g_signal_newv ("changed",
1376 G_TYPE_FROM_CLASS (gobject_class),
1377 G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS,
1379 NULL /* accumulator */,
1380 NULL /* accumulator data */,
1381 g_cclosure_marshal_VOID__VOID,
1382 G_TYPE_NONE /* return_type */,
1384 NULL /* param_types */);
1386 and the signal is emitted in <function>maman_file_write</function>:
1389 maman_file_write (MamanFile *self,
1390 const guchar *buffer,
1393 /* First write data. */
1395 /* Then, notify user of data written. */
1396 g_signal_emit (self, file_signals[CHANGED], 0 /* details */);
1399 As shown above, you can safely set the details parameter to zero if
1400 you do not know what it can be used for. For a discussion of what you
1401 could used it for, see <xref linkend="signal-detail"/>
1405 The signature of the signal handler in the above example is defined as
1406 <function>g_cclosure_marshal_VOID__VOID</function>. Its name follows
1407 a simple convention which encodes the function parameter and return value
1408 types in the function name. Specifically, the value in front of the
1409 double underscore is the type of the return value, while the value(s)
1410 after the double underscore denote the parameter types.
1414 The header <filename>gobject/gmarshal.h</filename> defines a set of
1415 commonly needed closures that one can use. If you want to have complex
1416 marshallers for your signals you should probably use glib-genmarshal
1417 to autogenerate them from a file containing their return and
1423 this is utterly wrong and should be completely removed - or rewritten
1424 with a better example than writing a buffer using synchronous signals.
1427 <title>How to provide more flexibility to users?</title>
1430 The previous implementation does the job but the signal facility of
1431 GObject can be used to provide even more flexibility to this file
1432 change notification mechanism. One of the key ideas is to make the
1433 process of writing data to the file part of the signal emission
1434 process to allow users to be notified either before or after the
1435 data is written to the file.
1439 To integrate the process of writing the data to the file into the
1440 signal emission mechanism, we can register a default class closure
1441 for this signal which will be invoked during the signal emission,
1442 just like any other user-connected signal handler.
1446 The first step to implement this idea is to change the signature of
1447 the signal: we need to pass around the buffer to write and its size.
1448 To do this, we use our own marshaller which will be generated
1449 through GLib's glib-genmarshal tool. We thus create a file named <filename>marshall.list</filename> which contains
1450 the following single line:
1454 and use the Makefile provided in <filename>sample/signal/Makefile</filename> to generate the file named
1455 <filename>maman-file-complex-marshall.c</filename>. This C file is finally included in
1456 <filename>maman-file-complex.c</filename>.
1460 Once the marshaller is present, we register the signal and its marshaller in the class_init function
1461 of the object <type>MamanFileComplex</type> (full source for this object is included in
1462 <filename>sample/signal/maman-file-complex.{h|c}</filename>):
1464 GClosure *default_closure;
1465 GType param_types[2];
1467 default_closure = g_cclosure_new (G_CALLBACK (default_write_signal_handler),
1468 (gpointer)0xdeadbeaf /* user_data */,
1469 NULL /* destroy_data */);
1471 param_types[0] = G_TYPE_POINTER;
1472 param_types[1] = G_TYPE_UINT;
1473 klass->write_signal_id =
1474 g_signal_newv ("write",
1475 G_TYPE_FROM_CLASS (g_class),
1476 G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS,
1477 default_closure /* class closure */,
1478 NULL /* accumulator */,
1479 NULL /* accu_data */,
1480 maman_file_complex_VOID__POINTER_UINT,
1481 G_TYPE_NONE /* return_type */,
1483 param_types /* param_types */);
1485 The code shown above first creates the closure which contains the code to complete the file write. This
1486 closure is registered as the default class_closure of the newly created signal.
1490 Of course, you need to implement completely the code for the default closure since I just provided
1494 default_write_signal_handler (GObject *obj, guint8 *buffer, guint size, gpointer user_data)
1496 g_assert (user_data == (gpointer)0xdeadbeaf);
1497 /* Here, we trigger the real file write. */
1498 g_print ("default signal handler: 0x%x %u\n", buffer, size);
1504 Finally, the client code must invoke the <function>maman_file_complex_write</function> function which
1505 triggers the signal emission:
1507 void maman_file_complex_write (MamanFileComplex *self, guint8 *buffer, guint size)
1510 g_signal_emit (self,
1511 MAMAN_FILE_COMPLEX_GET_CLASS (self)->write_signal_id,
1519 The client code (as shown in <filename>sample/signal/test.c</filename> and below) can now connect signal handlers before
1520 and after the file write is completed: since the default signal handler which does the write itself runs during the
1521 RUN_LAST phase of the signal emission, it will run after all handlers connected with <function><link linkend="g-signal-connect">g_signal_connect</link></function>
1522 and before all handlers connected with <function><link linkend="g-signal-connect-after">g_signal_connect_after</link></function>. If you intent to write a GObject
1523 which emits signals, I would thus urge you to create all your signals with the G_SIGNAL_RUN_LAST such that your users
1524 have a maximum of flexibility as to when to get the event. Here, we combined it with G_SIGNAL_NO_RECURSE and
1525 G_SIGNAL_NO_HOOKS to ensure our users will not try to do really weird things with our GObject. I strongly advise you
1526 to do the same unless you really know why (in which case you really know the inner workings of GSignal by heart and
1527 you are not reading this).
1532 static void complex_write_event_before (GObject *file, guint8 *buffer, guint size, gpointer user_data)
1534 g_assert (user_data == NULL);
1535 g_print ("Complex Write event before: 0x%x, %u\n", buffer, size);
1538 static void complex_write_event_after (GObject *file, guint8 *buffer, guint size, gpointer user_data)
1540 g_assert (user_data == NULL);
1541 g_print ("Complex Write event after: 0x%x, %u\n", buffer, size);
1544 static void test_file_complex (void)
1549 file = g_object_new (MAMAN_FILE_COMPLEX_TYPE, NULL);
1551 g_signal_connect (G_OBJECT (file), "write",
1552 (GCallback)complex_write_event_before,
1555 g_signal_connect_after (G_OBJECT (file), "write",
1556 (GCallback)complex_write_event_after,
1559 maman_file_complex_write (MAMAN_FILE_COMPLEX (file), buffer, 50);
1561 g_object_unref (G_OBJECT (file));
1564 The code above generates the following output on my machine:
1566 Complex Write event before: 0xbfffe280, 50
1567 default signal handler: 0xbfffe280 50
1568 Complex Write event after: 0xbfffe280, 50
1575 this is also utterly wrong on so many levels that I don't even want
1576 to enumerate them. it's also full of completely irrelevant footnotes
1577 about personal preferences demonstrating a severe lack of whatsoever
1578 clue. the whole idea of storing the signal ids inside the Class
1579 structure is so fundamentally flawed that I'll require a frontal
1580 lobotomy just to forget I've ever seen it.
1583 <title>How most people do the same thing with less code</title>
1585 <para>For many historic reasons related to how the ancestor of GObject used to work in GTK+ 1.x versions,
1586 there is a much <emphasis>simpler</emphasis>
1588 <para>I personally think that this method is horribly mind-twisting: it adds a new indirection
1589 which unnecessarily complicates the overall code path. However, because this method is widely used
1590 by all of GTK+ and GObject code, readers need to understand it. The reason why this is done that way
1591 in most of GTK+ is related to the fact that the ancestor of GObject did not provide any other way to
1592 create a signal with a default handler than this one. Some people have tried to justify that it is done
1593 that way because it is better, faster (I am extremely doubtful about the faster bit. As a matter of fact,
1594 the better bit also mystifies me ;-). I have the feeling no one really knows and everyone does it
1595 because they copy/pasted code from code which did the same. It is probably better to leave this
1596 specific trivia to hacker legends domain...
1599 way to create a signal with a default handler than to create
1600 a closure by hand and to use the <function><link linkend="g-signal-newv">g_signal_newv</link></function>.
1603 <para>For example, <function><link linkend="g-signal-new">g_signal_new</link></function> can be used to create a signal which uses a default
1604 handler which is stored in the class structure of the object. More specifically, the class structure
1605 contains a function pointer which is accessed during signal emission to invoke the default handler and
1606 the user is expected to provide to <function><link linkend="g-signal-new">g_signal_new</link></function> the offset from the start of the
1607 class structure to the function pointer.
1609 <para>I would like to point out here that the reason why the default handler of a signal is named everywhere
1610 a class_closure is probably related to the fact that it used to be really a function pointer stored in
1611 the class structure.
1616 <para>The following code shows the declaration of the <type>MamanFileSimple</type> class structure which contains
1617 the <function>write</function> function pointer.
1619 struct _MamanFileSimpleClass {
1620 GObjectClass parent;
1622 guint write_signal_id;
1624 /* signal default handlers */
1625 void (*write) (MamanFileSimple *self, guint8 *buffer, guint size);
1628 The <function>write</function> function pointer is initialized in the class_init function of the object
1629 to <function>default_write_signal_handler</function>:
1632 maman_file_simple_class_init (gpointer g_class,
1633 gpointer g_class_data)
1635 GObjectClass *gobject_class = G_OBJECT_CLASS (g_class);
1636 MamanFileSimpleClass *klass = MAMAN_FILE_SIMPLE_CLASS (g_class);
1638 klass->write = default_write_signal_handler;
1640 Finally, the signal is created with <function><link linkend="g-signal-new">g_signal_new</link></function> in the same class_init function:
1642 klass->write_signal_id =
1643 g_signal_new ("write",
1644 G_TYPE_FROM_CLASS (g_class),
1645 G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS,
1646 G_STRUCT_OFFSET (MamanFileSimpleClass, write),
1647 NULL /* accumulator */,
1648 NULL /* accu_data */,
1649 maman_file_complex_VOID__POINTER_UINT,
1650 G_TYPE_NONE /* return_type */,
1655 Of note, here, is the 4th argument to the function: it is an integer calculated by the <function><link linkend="G-STRUCT-OFFSET">G_STRUCT_OFFSET</link></function>
1656 macro which indicates the offset of the member <emphasis>write</emphasis> from the start of the
1657 <type>MamanFileSimpleClass</type> class structure.
1659 <para>GSignal uses this offset to create a special wrapper closure
1660 which first retrieves the target function pointer before calling it.
1666 While the complete code for this type of default handler looks less cluttered as shown in
1667 <filename>sample/signal/maman-file-simple.{h|c}</filename>, it contains numerous subtleties.
1668 The main subtle point which everyone must be aware of is that the signature of the default
1669 handler created that way does not have a user_data argument:
1670 <function>default_write_signal_handler</function> is different in
1671 <filename>sample/signal/maman-file-complex.c</filename> and in
1672 <filename>sample/signal/maman-file-simple.c</filename>.
1675 <para>If you have doubts about which method to use, I would advise you to use the second one which
1676 involves <function><link linkend="g-signal-new">g_signal_new</link></function> rather than <function><link linkend="g-signal-newv">g_signal_newv</link></function>:
1677 it is better to write code which looks like the vast majority of other GTK+/GObject code than to
1678 do it your own way. However, now, you know why.
1687 yet another pointless section. if we are scared of possible abuses
1688 from the users then we should not be mentioning it inside a tutorial
1689 for beginners. but, obviously, there's nothing to be afraid of - it's
1690 just that this section must be completely reworded.
1693 <title>How users can abuse signals (and why some think it is good)</title>
1695 <para>Now that you know how to create signals to which the users can connect easily and at any point in
1696 the signal emission process thanks to <function><link linkend="g-signal-connect">g_signal_connect</link></function>,
1697 <function><link linkend="g-signal-connect-after">g_signal_connect_after</link></function> and G_SIGNAL_RUN_LAST, it is time to look into how your
1698 users can and will screw you. This is also interesting to know how you too, can screw other people.
1699 This will make you feel good and eleet.
1705 <listitem><para>stop the emission of the signal at anytime</para></listitem>
1706 <listitem><para>override the default handler of the signal if it is stored as a function
1707 pointer in the class structure (which is the preferred way to create a default signal handler,
1708 as discussed in the previous section).</para></listitem>
1713 In both cases, the original programmer should be as careful as possible to write code which is
1714 resistant to the fact that the default handler of the signal might not able to run. This is obviously
1715 not the case in the example used in the previous sections since the write to the file depends on whether
1716 or not the default handler runs (however, this might be your goal: to allow the user to prevent the file
1717 write if he wishes to).
1721 If all you want to do is to stop the signal emission from one of the callbacks you connected yourself,
1722 you can call <function><link linkend="g-signal-stop-by-name">g_signal_stop_by_name</link></function>. Its use is very simple which is why I won't detail
1727 If the signal's default handler is just a class function pointer, it is also possible to override
1728 it yourself from the class_init function of a type which derives from the parent. That way, when the signal
1729 is emitted, the parent class will use the function provided by the child as a signal default handler.
1730 Of course, it is also possible (and recommended) to chain up from the child to the parent's default signal
1731 handler to ensure the integrity of the parent object.
1735 Overriding a class method and chaining up was demonstrated in <xref linkend="howto-gobject-methods"/>
1736 which is why I won't bother to show exactly how to do it here again.
1747 <title>Warning on signal creation and default closure</title>
1750 Most of the existing code I have seen up to now (in both GTK+, GNOME libraries and
1751 many GTK+ and GNOME applications) using signals uses a small
1752 variation of the default handler pattern I have shown in the previous section.
1756 Usually, the <function><link linkend="g-signal-new">g_signal_new</link></function> function is preferred over
1757 <function><link linkend="g-signal-newv">g_signal_newv</link></function>. When <function><link linkend="g-signal-new">g_signal_new</link></function>
1758 is used, the default closure is exported as a class function. For example,
1759 <filename>gobject.h</filename> contains the declaration of <link linkend="GObjectClass"><type>GObjectClass</type></link>
1760 whose notify class function is the default handler for the <emphasis>notify</emphasis>
1763 struct _GObjectClass
1765 GTypeClass g_type_class;
1767 /* class methods and other stuff. */
1770 void (*notify) (GObject *object,
1777 <filename>gobject.c</filename>'s <function><link linkend="g-object-do-class-init">g_object_do_class_init</link></function> function
1778 registers the <emphasis>notify</emphasis> signal and initializes this class function
1782 g_object_do_class_init (GObjectClass *class)
1787 class->notify = NULL;
1789 gobject_signals[NOTIFY] =
1790 g_signal_new ("notify",
1791 G_TYPE_FROM_CLASS (class),
1792 G_SIGNAL_RUN_FIRST | G_SIGNAL_NO_RECURSE | G_SIGNAL_DETAILED | G_SIGNAL_NO_HOOKS,
1793 G_STRUCT_OFFSET (GObjectClass, notify),
1795 g_cclosure_marshal_VOID__PARAM,
1800 <function><link linkend="g-signal-new">g_signal_new</link></function> creates a <link linkend="GClosure"><type>GClosure</type></link> which dereferences the
1801 type's class structure to access the class function pointer and invoke it if it not NULL. The
1802 class function is ignored it is set to NULL.
1806 To understand the reason for such a complex scheme to access the signal's default handler,
1807 you must remember the whole reason for the use of these signals. The goal here is to delegate
1808 a part of the process to the user without requiring the user to subclass the object to override
1809 one of the class functions. The alternative to subclassing, that is, the use of signals
1810 to delegate processing to the user, is, however, a bit less optimal in terms of speed: rather
1811 than just dereferencing a function pointer in a class structure, you must start the whole
1812 process of signal emission which is a bit heavyweight.
1816 This is why some people decided to use class functions for some signal's default handlers:
1817 rather than having users connect a handler to the signal and stop the signal emission
1818 from within that handler, you just need to override the default class function which is
1819 supposedly more efficient.