1 <?xml version='1.0' encoding="ISO-8859-1"?>
2 <!DOCTYPE part PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
3 "http://www.oasis-open.org/docbook/xml/4.1.2/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>
48 Pick a name convention for your headers and source code and stick to it:
50 <listitem><para>use a dash to separate the prefix from the typename:
51 <filename>maman-bar.h</filename> and <filename>maman-bar.c</filename>
52 (this is the convention used by Nautilus and most GNOME libraries).</para></listitem>
53 <listitem><para>use an underscore to separate the prefix from the
54 typename: <filename>maman_bar.h</filename> and
55 <filename>maman_bar.c</filename>.</para></listitem>
56 <listitem><para>Do not separate the prefix from the typename:
57 <filename>mamanbar.h</filename> and <filename>mamanbar.c</filename>.
58 (this is the convention used by GTK+)</para></listitem>
60 Some people like the first two solutions better: it makes reading file
61 names easier for those with poor eyesight.
65 When you need some private (internal) declarations in several
66 (sub)classes, you can define them in a private header file which
67 is often named by appending the <emphasis>private</emphasis> keyword
68 to the public header name. For example, one could use
69 <filename>maman-bar-private.h</filename>,
70 <filename>maman_bar_private.h</filename> or
71 <filename>mamanbarprivate.h</filename>. Typically, such private header
72 files are not installed.
76 The basic conventions for any header which exposes a GType are described
77 in <xref linkend="gtype-conventions"/>. Most GObject-based code also
78 obeys one of of the following conventions: pick one and stick to it.
81 If you want to declare a type named bar with prefix maman, name the type instance
82 <function>MamanBar</function> and its class <function>MamanBarClass</function>
83 (name is case-sensitive). It is customary to declare them with code similar to the
87 * Copyright/Licensing information.
91 #ifndef __MAMAN_BAR_H__
92 #define __MAMAN_BAR_H__
94 #include <glib-object.h>
96 * Potentially, include other headers on which this header depends.
102 #define MAMAN_TYPE_BAR (maman_bar_get_type ())
103 #define MAMAN_BAR(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_TYPE_BAR, MamanBar))
104 #define MAMAN_IS_BAR(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_TYPE_BAR))
105 #define MAMAN_BAR_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), MAMAN_TYPE_BAR, MamanBarClass))
106 #define MAMAN_IS_BAR_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), MAMAN_TYPE_BAR))
107 #define MAMAN_BAR_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), MAMAN_TYPE_BAR, MamanBarClass))
109 typedef struct _MamanBar MamanBar;
110 typedef struct _MamanBarClass MamanBarClass;
114 GObject parent_instance;
116 /* instance members */
119 struct _MamanBarClass
121 GObjectClass parent_class;
126 /* used by MAMAN_TYPE_BAR */
127 GType maman_bar_get_type (void);
130 * Method definitions.
133 #endif /* __MAMAN_BAR_H__ */
137 Most GTK+ types declare their private fields in the public header
138 with a /* private */ comment, relying on their user's intelligence
139 not to try to play with these fields. Fields not marked private
140 are considered public by default. The /* protected */ comment
141 (same semantics as those of C++) is also used, mainly in the GType
142 library, in code written by Tim Janik.
146 GObject parent_instance;
148 /*< private >*/
154 All of Nautilus code and a lot of GNOME libraries use private
155 indirection members, as described by Herb Sutter in his Pimpl
156 articles(see <ulink url="http://www.gotw.ca/gotw/024.htm">Compilation Firewalls</ulink>
157 and <ulink url="http://www.gotw.ca/gotw/028.htm">The Fast Pimpl Idiom</ulink>:
158 he summarizes the different issues better than I will).
160 typedef struct _MamanBarPrivate MamanBarPrivate;
164 GObject parent_instance;
166 /*< private >*/
167 MamanBarPrivate *priv;
170 <note><simpara>Do not call this <varname>private</varname>, as
171 that is a registered c++ keyword.</simpara></note>
173 The private structure is then defined in the .c file, using the
174 g_type_class_add_private() function to notify the presence of
175 a private memory area for each instance and it can either
176 be retrieved using <function>G_TYPE_INSTANCE_GET_PRIVATE()</function>
177 each time is needed, or assigned to the <literal>priv</literal>
178 member of the instance structure inside the object's
179 <function>init</function> function.
181 #define MAMAN_BAR_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), MAMAN_TYPE_BAR, MamanBarPrivate))
183 struct _MamanBarPrivate
189 maman_bar_class_init (MamanBarClass *klass)
191 g_type_class_add_private (klass, sizeof (MamanBarPrivate));
195 maman_bar_init (MamanBar *self)
197 MamanBarPrivate *priv;
199 self->priv = priv = MAMAN_BAR_GET_PRIVATE (self);
207 You don't need to free or allocate the private structure, only the
208 objects or pointers that it may contain. Another advantage of this
209 to the previous version is that is lessens memory fragmentation,
210 as the public and private parts of the instance memory are
217 Finally, there are different header include conventions. Again, pick one
218 and stick to it. I personally use indifferently any of the two, depending
219 on the codebase I work on: the rule, as always, is consistency.
222 Some people add at the top of their headers a number of #include
223 directives to pull in all the headers needed to compile client
224 code. This allows client code to simply #include "maman-bar.h".
227 Other do not #include anything and expect the client to #include
228 themselves the headers they need before including your header. This
229 speeds up compilation because it minimizes the amount of
230 pre-processor work. This can be used in conjunction with the
231 re-declaration of certain unused types in the client code to
232 minimize compile-time dependencies and thus speed up compilation.
239 <sect1 id="howto-gobject-code">
240 <title>Boilerplate code</title>
243 In your code, the first step is to #include the needed headers: depending
244 on your header include strategy, this can be as simple as
245 <literal>#include "maman-bar.h"</literal> or as complicated as tens
246 of #include lines ending with <literal>#include "maman-bar.h"</literal>:
249 * Copyright information
252 #include "maman-bar.h"
254 /* If you use Pimpls, include the private structure
255 * definition here. Some people create a maman-bar-private.h header
256 * which is included by the maman-bar.c file and which contains the
257 * definition for this private structure.
259 struct _MamanBarPrivate {
265 * forward definitions
271 Call the <function>G_DEFINE_TYPE</function> macro using the name
272 of the type, the prefix of the functions and the parent GType to
273 reduce the amount of boilerplate needed. This macro will:
276 <listitem><simpara>implement the <function>maman_bar_get_type</function>
277 function</simpara></listitem>
278 <listitem><simpara>define a parent class pointer accessible from
279 the whole .c file</simpara></listitem>
283 G_DEFINE_TYPE (MamanBar, maman_bar, G_TYPE_OBJECT);
288 It is also possible to use the
289 <function>G_DEFINE_TYPE_WITH_CODE</function> macro to control the
290 get_type function implementation - for instance, to add a call to
291 <function>G_IMPLEMENT_INTERFACE</function> macro which will
292 call the <function>g_type_implement_interface</function> function.
296 <sect1 id="howto-gobject-construction">
297 <title>Object Construction</title>
300 People often get confused when trying to construct their GObjects because of the
301 sheer number of different ways to hook into the objects's construction process: it is
302 difficult to figure which is the <emphasis>correct</emphasis>, recommended way.
306 <xref linkend="gobject-construction-table"/> shows what user-provided functions
307 are invoked during object instantiation and in which order they are invoked.
308 A user looking for the equivalent of the simple C++ constructor function should use
309 the instance_init method. It will be invoked after all the parent's instance_init
310 functions have been invoked. It cannot take arbitrary construction parameters
311 (as in C++) but if your object needs arbitrary parameters to complete initialization,
312 you can use construction properties.
316 Construction properties will be set only after all instance_init functions have run.
317 No object reference will be returned to the client of <function><link linkend="g-object-new">g_object_new</link></function>
318 until all the construction properties have been set.
322 As such, I would recommend writing the following code first:
325 maman_bar_init (MamanBar *self)
327 self->priv = MAMAN_BAR_GET_PRIVATE (self);
329 /* initialize all public and private members to reasonable default values. */
331 /* If you need specific construction properties to complete initialization,
332 * delay initialization completion until the property is set.
339 Now, if you need special construction properties, install the properties in the class_init function,
340 override the set and get methods and implement the get and set methods as described in
341 <xref linkend="gobject-properties"/>. Make sure that these properties use a construct only
342 <link linkend="GParamSpec"><type>GParamSpec</type></link> by setting the param spec's flag field to G_PARAM_CONSTRUCT_ONLY: this helps
343 GType ensure that these properties are not set again later by malicious user code.
344 <informalexample><programlisting>
353 static GParamSpec *obj_properties[N_PROPERTIES] = { NULL, };
356 bar_class_init (MamanBarClass *klass)
358 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
360 gobject_class->set_property = bar_set_property;
361 gobject_class->get_property = bar_get_property;
363 obj_properties[PROP_MAMAN] =
364 g_param_spec_string ("maman",
365 "Maman construct prop",
367 "no-name-set" /* default value */,
368 G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE);
370 g_object_class_install_properties (gobject_class,
374 </programlisting></informalexample>
375 If you need this, make sure you can build and run code similar to the code shown above. Make sure
376 your construct properties can set correctly during construction, make sure you cannot set them
377 afterwards and make sure that if your users do not call <function><link linkend="g-object-new">g_object_new</link></function>
378 with the required construction properties, these will be initialized with the default values.
382 I consider good taste to halt program execution if a construction property is set its
383 default value. This allows you to catch client code which does not give a reasonable
384 value to the construction properties. Of course, you are free to disagree but you
385 should have a good reason to do so.
389 Some people sometimes need to construct their object but only after
390 the construction properties have been set. This is possible through
391 the use of the constructor class method as described in
392 <xref linkend="gobject-instantiation"/> or, more simply, using
393 the constructed class method available since GLib 2.12.
397 <sect1 id="howto-gobject-destruction">
398 <title>Object Destruction</title>
401 Again, it is often difficult to figure out which mechanism to use to
402 hook into the object's destruction process: when the last
403 <function><link linkend="g-object-unref">g_object_unref</link></function>
404 function call is made, a lot of things happen as described in
405 <xref linkend="gobject-destruction-table"/>.
409 The destruction process of your object might be split in two different
410 phases: dispose and the finalize.
412 #define MAMAN_BAR_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), MAMAN_TYPE_BAR, MamanBarPrivate))
414 struct _MamanBarPrivate
421 G_DEFINE_TYPE (MamanBar, maman_bar, G_TYPE_OBJECT);
424 maman_bar_dispose (GObject *gobject)
426 MamanBar *self = MAMAN_BAR (gobject);
429 * In dispose, you are supposed to free all types referenced from this
430 * object which might themselves hold a reference to self. Generally,
431 * the most simple solution is to unref all members on which you own a
435 /* dispose might be called multiple times, so we must guard against
436 * calling g_object_unref() on an invalid GObject.
438 if (self->priv->an_object)
440 g_object_unref (self->priv->an_object);
442 self->priv->an_object = NULL;
445 /* Chain up to the parent class */
446 G_OBJECT_CLASS (maman_bar_parent_class)->dispose (gobject);
450 maman_bar_finalize (GObject *gobject)
452 MamanBar *self = MAMAN_BAR (gobject);
454 g_free (self->priv->a_string);
456 /* Chain up to the parent class */
457 G_OBJECT_CLASS (maman_bar_parent_class)->finalize (gobject);
461 maman_bar_class_init (MamanBarClass *klass)
463 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
465 gobject_class->dispose = maman_bar_dispose;
466 gobject_class->finalize = maman_bar_finalize;
468 g_type_class_add_private (klass, sizeof (MamanBarPrivate));
472 maman_bar_init (MamanBar *self);
474 self->priv = MAMAN_BAR_GET_PRIVATE (self);
476 self->priv->an_object = g_object_new (MAMAN_TYPE_BAZ, NULL);
477 self->priv->a_string = g_strdup ("Maman");
483 Add similar code to your GObject, make sure the code still builds
484 and runs: dispose and finalize must be called during the last unref.
488 It is possible that object methods might be invoked after dispose is
489 run and before finalize runs. GObject does not consider this to be a
490 program error: you must gracefully detect this and neither crash nor
495 <sect1 id="howto-gobject-methods">
496 <title>Object methods</title>
499 Just as with C++, there are many different ways to define object
500 methods and extend them: the following list and sections draw on
501 C++ vocabulary. (Readers are expected to know basic C++ buzzwords.
502 Those who have not had to write C++ code recently can refer to e.g.
503 <ulink url="http://www.cplusplus.com/doc/tutorial/"/> to refresh
507 non-virtual public methods,
510 virtual public methods and
513 virtual private methods
519 <title>Non-virtual public methods</title>
522 These are the simplest: you want to provide a simple method which
523 can act on your object. All you need to do is to provide a function
524 prototype in the header and an implementation of that prototype
527 /* declaration in the header. */
528 void maman_bar_do_action (MamanBar *self, /* parameters */);
530 /* implementation in the source file */
532 maman_bar_do_action (MamanBar *self, /* parameters */)
534 g_return_if_fail (MAMAN_IS_BAR (self));
541 <para>There is really nothing scary about this.</para>
545 <title>Virtual public methods</title>
548 This is the preferred way to create polymorphic GObjects. All you
549 need to do is to define the common method and its class function in
550 the public header, implement the common method in the source file
551 and re-implement the class function in each object which inherits
554 /* declaration in maman-bar.h. */
555 struct _MamanBarClass
557 GObjectClass parent_class;
560 void (*do_action) (MamanBar *self, /* parameters */);
563 void maman_bar_do_action (MamanBar *self, /* parameters */);
565 /* implementation in maman-bar.c */
567 maman_bar_do_action (MamanBar *self, /* parameters */)
569 g_return_if_fail (MAMAN_IS_BAR (self));
571 MAMAN_BAR_GET_CLASS (self)->do_action (self, /* parameters */);
574 The code above simply redirects the do_action call to the relevant
575 class function. Some users, concerned about performance, do not
576 provide the <function>maman_bar_do_action</function> wrapper function
577 and require users to dereference the class pointer themselves. This
578 is not such a great idea in terms of encapsulation and makes it
579 difficult to change the object's implementation afterwards, should
584 Other users, also concerned by performance issues, declare
585 the <function>maman_bar_do_action</function> function inline in the
586 header file. This, however, makes it difficult to change the
587 object's implementation later (although easier than requiring users
588 to directly dereference the class function) and is often difficult
589 to write in a portable way (the <emphasis>inline</emphasis> keyword
590 is part of the C99 standard but not every compiler supports it).
594 In doubt, unless a user shows you hard numbers about the performance
595 cost of the function call, just implement <function>maman_bar_do_action</function>
600 Please, note that it is possible for you to provide a default
601 implementation for this class method in the object's
602 <function>class_init</function> function: initialize the
603 klass->do_action field to a pointer to the actual implementation.
604 You can also make this class method pure virtual by initializing
605 the klass->do_action field to NULL:
608 maman_bar_real_do_action_two (MamanBar *self, /* parameters */)
610 /* Default implementation for the virtual method. */
614 maman_bar_class_init (BarClass *klass)
616 /* pure virtual method: mandates implementation in children. */
617 klass->do_action_one = NULL;
619 /* merely virtual method. */
620 klass->do_action_two = maman_bar_real_do_action_two;
624 maman_bar_do_action_one (MamanBar *self, /* parameters */)
626 g_return_if_fail (MAMAN_IS_BAR (self));
628 MAMAN_BAR_GET_CLASS (self)->do_action_one (self, /* parameters */);
632 maman_bar_do_action_two (MamanBar *self, /* parameters */)
634 g_return_if_fail (MAMAN_IS_BAR (self));
636 MAMAN_BAR_GET_CLASS (self)->do_action_two (self, /* parameters */);
643 <title>Virtual private Methods</title>
646 These are very similar to Virtual Public methods. They just don't
647 have a public function to call the function directly. The header
648 file contains only a declaration of the class function:
650 /* declaration in maman-bar.h. */
651 struct _MamanBarClass
656 void (* helper_do_specific_action) (MamanBar *self, /* parameters */);
659 void maman_bar_do_any_action (MamanBar *self, /* parameters */);
661 These class functions are often used to delegate part of the job
664 /* this accessor function is static: it is not exported outside of this file. */
666 maman_bar_do_specific_action (MamanBar *self, /* parameters */)
668 MAMAN_BAR_GET_CLASS (self)->do_specific_action (self, /* parameters */);
672 maman_bar_do_any_action (MamanBar *self, /* parameters */)
674 /* random code here */
677 * Try to execute the requested action. Maybe the requested action
678 * cannot be implemented here. So, we delegate its implementation
679 * to the child class:
681 maman_bar_do_specific_action (self, /* parameters */);
683 /* other random code here */
689 Again, it is possible to provide a default implementation for this
690 private virtual class function:
693 maman_bar_class_init (MamanBarClass *klass)
695 /* pure virtual method: mandates implementation in children. */
696 klass->do_specific_action_one = NULL;
698 /* merely virtual method. */
699 klass->do_specific_action_two = maman_bar_real_do_specific_action_two;
705 Children can then implement the subclass with code such as:
708 maman_bar_subtype_class_init (MamanBarSubTypeClass *klass)
710 MamanBarClass *bar_class = MAMAN_BAR_CLASS (klass);
712 /* implement pure virtual class function. */
713 bar_class->do_specific_action_one = maman_bar_subtype_do_specific_action_one;
720 <sect1 id="howto-gobject-chainup">
721 <title>Chaining up</title>
723 <para>Chaining up is often loosely defined by the following set of
726 <listitem><para>Parent class A defines a public virtual method named <function>foo</function> and
727 provides a default implementation.</para></listitem>
728 <listitem><para>Child class B re-implements method <function>foo</function>.</para></listitem>
729 <listitem><para>In the method B::foo, the child class B calls its parent class method A::foo.</para></listitem>
731 There are many uses to this idiom:
733 <listitem><para>You need to change the behaviour of a class without modifying its code. You create
734 a subclass to inherit its implementation, re-implement a public virtual method to modify the behaviour
735 slightly and chain up to ensure that the previous behaviour is not really modified, just extended.
737 <listitem><para>You are lazy, you have access to the source code of the parent class but you don't want
738 to modify it to add method calls to new specialized method calls: it is faster to hack the child class
739 to chain up than to modify the parent to call down.</para></listitem>
740 <listitem><para>You need to implement the Chain Of Responsibility pattern: each object of the inheritance
741 tree chains up to its parent (typically, at the beginning or the end of the method) to ensure that
742 they each handler is run in turn.</para></listitem>
744 I am personally not really convinced any of the last two uses are really a good idea but since this
745 programming idiom is often used, this section attempts to explain how to implement it.
749 To explicitly chain up to the implementation of the virtual method in the parent class,
750 you first need a handle to the original parent class structure. This pointer can then be used to
751 access the original class function pointer and invoke it directly.
754 The <emphasis>original</emphasis> adjective used in this sentence is not innocuous. To fully
755 understand its meaning, you need to recall how class structures are initialized: for each object type,
756 the class structure associated to this object is created by first copying the class structure of its
757 parent type (a simple <function>memcpy</function>) and then by invoking the class_init callback on
758 the resulting class structure. Since the class_init callback is responsible for overwriting the class structure
759 with the user re-implementations of the class methods, we cannot merely use the modified copy of the parent class
760 structure stored in our derived instance. We want to get a copy of the class structure of an instance of the parent
766 <para>The function <function><link linkend="g-type-class-peek-parent">g_type_class_peek_parent</link></function> is used to access the original parent
767 class structure. Its input is a pointer to the class of the derived object and it returns a pointer
768 to the original parent class structure. The code below shows how you could use it:
771 b_method_to_call (B *obj, int a)
774 AClass *parent_class;
776 klass = B_GET_CLASS (obj);
777 parent_class = g_type_class_peek_parent (klass);
779 /* do stuff before chain up */
781 parent_class->method_to_call (obj, a);
783 /* do stuff after chain up */
791 <!-- End Howto GObject -->
793 <chapter id="howto-interface">
794 <title>How to define and implement interfaces</title>
796 <sect1 id="howto-interface-define">
797 <title>How to define interfaces</title>
800 The bulk of interface definition has already been shown in <xref linkend="gtype-non-instantiable-classed"/>
801 but I feel it is needed to show exactly how to create an interface.
805 As above, the first step is to get the header right:
807 #ifndef __MAMAN_IBAZ_H__
808 #define __MAMAN_IBAZ_H__
810 #include <glib-object.h>
812 #define MAMAN_TYPE_IBAZ (maman_ibaz_get_type ())
813 #define MAMAN_IBAZ(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_TYPE_IBAZ, MamanIbaz))
814 #define MAMAN_IS_IBAZ(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_TYPE_IBAZ))
815 #define MAMAN_IBAZ_GET_INTERFACE(inst) (G_TYPE_INSTANCE_GET_INTERFACE ((inst), MAMAN_TYPE_IBAZ, MamanIbazInterface))
818 typedef struct _MamanIbaz MamanIbaz; /* dummy object */
819 typedef struct _MamanIbazInterface MamanIbazInterface;
821 struct _MamanIbazInterface
823 GTypeInterface parent_iface;
825 void (*do_action) (MamanIbaz *self);
828 GType maman_ibaz_get_type (void);
830 void maman_ibaz_do_action (MamanIbaz *self);
832 #endif /* __MAMAN_IBAZ_H__ */
834 This code is the same as the code for a normal <link linkend="GType"><type>GType</type></link>
835 which derives from a <link linkend="GObject"><type>GObject</type></link> except for a few details:
838 The <function>_GET_CLASS</function> macro is called <function>_GET_INTERFACE</function>
839 and not implemented with <function><link linkend="G-TYPE-INSTANCE-GET-CLASS:CAPS">G_TYPE_INSTANCE_GET_CLASS</link></function>
840 but with <function><link linkend="G-TYPE-INSTANCE-GET-INTERFACE:CAPS">G_TYPE_INSTANCE_GET_INTERFACE</link></function>.
843 The instance type, <type>MamanIbaz</type> is not fully defined: it is
844 used merely as an abstract type which represents an instance of
845 whatever object which implements the interface.
848 The parent of the <type>MamanIbazInterface</type> is not
849 <type>GObjectClass</type> but <type>GTypeInterface</type>.
855 The implementation of the <type>MamanIbaz</type> type itself is trivial:
857 <listitem><para><function>maman_ibaz_get_type</function> registers the
858 type in the type system.
860 <listitem><para><function>maman_ibaz_base_init</function> is expected
861 to register the interface's signals if there are any (we will see a bit
862 (later how to use them). Make sure to use a static local boolean variable
863 to make sure not to run the initialization code twice (as described in
864 <xref linkend="gtype-non-instantiable-classed-init"/>,
865 <function>base_init</function> is run once for each interface implementation
866 instantiation)</para></listitem>
867 <listitem><para><function>maman_ibaz_do_action</function> dereferences
868 the class structure to access its associated class function and calls it.
873 maman_ibaz_base_init (gpointer g_class)
875 static gboolean is_initialized = FALSE;
879 /* add properties and signals to the interface here */
881 is_initialized = TRUE;
886 maman_ibaz_get_type (void)
888 static GType iface_type = 0;
891 const GTypeInfo info = {
892 sizeof (MamanIbazInterface),
893 maman_ibaz_base_init, /* base_init */
894 NULL, /* base_finalize */
897 iface_type = g_type_register_static (G_TYPE_INTERFACE, "MamanIbaz",
905 maman_ibaz_do_action (MamanIbaz *self)
907 g_return_if_fail (MAMAN_IS_IBAZ (self));
909 MAMAN_IBAZ_GET_INTERFACE (self)->do_action (self);
915 <sect1 id="howto-interface-implement">
916 <title>How To define implement an Interface?</title>
919 Once the interface is defined, implementing it is rather trivial.
923 The first step is to define a normal GObject class, like:
925 #ifndef __MAMAN_BAZ_H__
926 #define __MAMAN_BAZ_H__
928 #include <glib-object.h>
930 #define MAMAN_TYPE_BAZ (maman_baz_get_type ())
931 #define MAMAN_BAZ(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_TYPE_BAZ, Mamanbaz))
932 #define MAMAN_IS_BAZ(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_TYPE_BAZ))
933 #define MAMAN_BAZ_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), MAMAN_TYPE_BAZ, MamanbazClass))
934 #define MAMAN_IS_BAZ_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), MAMAN_TYPE_BAZ))
935 #define MAMAN_BAZ_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), MAMAN_TYPE_BAZ, MamanbazClass))
938 typedef struct _MamanBaz MamanBaz;
939 typedef struct _MamanBazClass MamanBazClass;
943 GObject parent_instance;
948 struct _MamanBazClass
950 GObjectClass parent_class;
953 GType maman_baz_get_type (void);
955 #endif /* __MAMAN_BAZ_H__ */
957 There is clearly nothing specifically weird or scary about this header:
958 it does not define any weird API or derives from a weird type.
962 The second step is to implement <type>MamanBaz</type> by defining
963 its GType. Instead of using <function>G_DEFINE_TYPE</function> we
964 use <function>G_DEFINE_TYPE_WITH_CODE</function> and the
965 <function>G_IMPLEMENT_INTERFACE</function> macros.
967 static void maman_ibaz_interface_init (MamanIbazInterface *iface);
969 G_DEFINE_TYPE_WITH_CODE (MamanBar, maman_bar, G_TYPE_OBJECT,
970 G_IMPLEMENT_INTERFACE (MAMAN_TYPE_IBAZ,
971 maman_ibaz_interface_init));
973 This definition is very much like all the similar functions we looked
974 at previously. The only interface-specific code present here is the call
975 to <function>G_IMPLEMENT_INTERFACE</function>.
978 <note><para>Classes can implement multiple interfaces by using multiple
979 calls to <function>G_IMPLEMENT_INTERFACE</function> inside the call
980 to <function>G_DEFINE_TYPE_WITH_CODE</function>.</para></note>
983 <function>maman_baz_interface_init</function>, the interface
984 initialization function: inside it every virtual method of the interface
985 must be assigned to its implementation:
988 maman_baz_do_action (MamanBaz *self)
990 g_print ("Baz implementation of IBaz interface Action: 0x%x.\n",
991 self->instance_member);
995 maman_ibaz_interface_init (MamanIbazInterface *iface)
997 iface->do_action = baz_do_action;
1001 maman_baz_init (MamanBaz *self)
1003 MamanBaz *self = MAMAN_BAZ (instance);
1004 self->instance_member = 0xdeadbeaf;
1012 <title>Interface definition prerequisites</title>
1015 To specify that an interface requires the presence of other interfaces
1016 when implemented, GObject introduces the concept of
1017 <emphasis>prerequisites</emphasis>: it is possible to associate
1018 a list of prerequisite interfaces to an interface. For example, if
1019 object A wishes to implement interface I1, and if interface I1 has a
1020 prerequisite on interface I2, A has to implement both I1 and I2.
1024 The mechanism described above is, in practice, very similar to
1025 Java's interface I1 extends interface I2. The example below shows
1026 the GObject equivalent:
1028 /* inside the GType function of the MamanIbar interface */
1029 type = g_type_register_static (G_TYPE_INTERFACE, "MamanIbar", &info, 0);
1031 /* Make the MamanIbar interface require MamanIbaz interface. */
1032 g_type_interface_add_prerequisite (type, MAMAN_TYPE_IBAZ);
1034 The code shown above adds the MamanIbaz interface to the list of
1035 prerequisites of MamanIbar while the code below shows how an
1036 implementation can implement both interfaces and register their
1040 maman_ibar_do_another_action (MamanIbar *ibar)
1042 MamanBar *self = MAMAN_BAR (ibar);
1044 g_print ("Bar implementation of IBar interface Another Action: 0x%x.\n",
1045 self->instance_member);
1049 maman_ibar_interface_init (MamanIbarInterface *iface)
1051 iface->do_another_action = maman_ibar_do_another_action;
1055 maman_ibaz_do_action (MamanIbaz *ibaz)
1057 MamanBar *self = MAMAN_BAR (ibaz);
1059 g_print ("Bar implementation of IBaz interface Action: 0x%x.\n",
1060 self->instance_member);
1064 maman_ibaz_interface_init (MamanIbazInterface *iface)
1066 iface->do_action = maman_ibaz_do_action;
1070 maman_bar_class_init (MamanBarClass *klass)
1076 maman_bar_init (MamanBar *self)
1078 self->instance_member = 0x666;
1081 G_DEFINE_TYPE_WITH_CODE (MamanBar, maman_bar, G_TYPE_OBJECT,
1082 G_IMPLEMENT_INTERFACE (MAMAN_TYPE_IBAZ,
1083 maman_ibaz_interface_init)
1084 G_IMPLEMENT_INTERFACE (MAMAN_TYPE_IBAR,
1085 maman_ibar_interface_init));
1087 It is very important to notice that the order in which interface
1088 implementations are added to the main object is not random:
1089 <function><link linkend="g-type-add-interface-static">g_type_add_interface_static</link></function>,
1090 which is called by <function>G_IMPLEMENT_INTERFACE</function>, must be
1091 invoked first on the interfaces which have no prerequisites and then on
1096 <sect1 id="howto-interface-properties">
1097 <title>Interface Properties</title>
1100 Starting from version 2.4 of GLib, GObject interfaces can also have
1101 properties. Declaration of the interface properties is similar to
1102 declaring the properties of ordinary GObject types as explained in
1103 <xref linkend="gobject-properties"/>,
1104 except that <function><link linkend="g-object-interface-install-property">g_object_interface_install_property</link></function> is used to
1105 declare the properties instead of <function><link linkend="g-object-class-install-property">g_object_class_install_property</link></function>.
1109 To include a property named 'name' of type <type>string</type> in the
1110 <type>maman_ibaz</type> interface example code above, we only need to
1114 That really is one line extended to six for the sake of clarity
1117 line in the <function>maman_ibaz_base_init</function>
1120 The <function><link linkend="g-object-interface-install-property">g_object_interface_install_property</link></function>
1121 can also be called from <function>class_init</function> but it must
1122 not be called after that point.
1128 maman_ibaz_base_init (gpointer g_iface)
1130 static gboolean is_initialized = FALSE;
1132 if (!is_initialized)
1134 g_object_interface_install_property (g_iface,
1135 g_param_spec_string ("name",
1137 "Name of the MamanIbaz",
1139 G_PARAM_READWRITE));
1140 is_initialized = TRUE;
1147 One point worth noting is that the declared property wasn't assigned an
1148 integer ID. The reason being that integer IDs of properties are used
1149 only inside the get and set methods and since interfaces do not
1150 implement properties, there is no need to assign integer IDs to
1151 interface properties.
1155 An implementation shall declare and define it's properties in the usual
1156 way as explained in <xref linkend="gobject-properties"/>, except for one
1157 small change: it must declare the properties of the interface it
1158 implements using <function><link linkend="g-object-class-override-property">g_object_class_override_property</link></function>
1159 instead of <function><link linkend="g-object-class-install-property">g_object_class_install_property</link></function>.
1160 The following code snippet shows the modifications needed in the
1161 <type>MamanBaz</type> declaration and implementation above:
1166 GObject parent_instance;
1168 gint instance_member;
1180 maman_baz_set_property (GObject *object,
1182 const GValue *value,
1185 MamanBaz *baz = MAMAN_BAZ (object);
1192 baz->name = g_value_dup_string (value);
1196 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1202 maman_baz_get_property (GObject *object,
1207 MamanBaz *baz = MAMAN_BAZ (object);
1212 g_value_set_string (value, baz->name);
1216 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1222 maman_baz_class_init (MamanBazClass *klass)
1224 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1226 gobject_class->set_property = maman_baz_set_property;
1227 gobject_class->get_property = maman_baz_get_property;
1229 g_object_class_override_property (gobject_class, PROP_NAME, "name");
1237 <!-- End Howto Interfaces -->
1239 <chapter id="howto-signals">
1240 <title>How to create and use signals</title>
1243 The signal system which was built in GType is pretty complex and
1244 flexible: it is possible for its users to connect at runtime any
1245 number of callbacks (implemented in any language for which a binding
1248 <para>A Python callback can be connected to any signal on any
1252 to any signal and to stop the emission of any signal at any
1253 state of the signal emission process. This flexibility makes it
1254 possible to use GSignal for much more than just emit signals which
1255 can be received by numerous clients.
1258 <sect1 id="howto-simple-signals">
1259 <title>Simple use of signals</title>
1262 The most basic use of signals is to implement simple event
1263 notification: for example, if we have a MamanFile object, and
1264 if this object has a write method, we might wish to be notified
1265 whenever someone has changed something via our MamanFile instance.
1266 The code below shows how the user can connect a callback to the
1269 file = g_object_new (MAMAN_FILE_TYPE, NULL);
1271 g_signal_connect (file, "changed", G_CALLBACK (changed_event), NULL);
1273 maman_file_write (file, buffer, strlen (buffer));
1278 The <type>MamanFile</type> signal is registered in the class_init
1281 file_signals[CHANGED] =
1282 g_signal_newv ("changed",
1283 G_TYPE_FROM_CLASS (gobject_class),
1284 G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS,
1286 NULL /* accumulator */,
1287 NULL /* accumulator data */,
1288 g_cclosure_marshal_VOID__VOID,
1289 G_TYPE_NONE /* return_type */,
1291 NULL /* param_types */);
1293 and the signal is emitted in <function>maman_file_write</function>:
1296 maman_file_write (MamanFile *self,
1297 const guchar *buffer,
1300 /* First write data. */
1302 /* Then, notify user of data written. */
1303 g_signal_emit (self, file_signals[CHANGED], 0 /* details */);
1306 As shown above, you can safely set the details parameter to zero if
1307 you do not know what it can be used for. For a discussion of what you
1308 could used it for, see <xref linkend="signal-detail"/>
1312 The signature of the signal handler in the above example is defined as
1313 <function>g_cclosure_marshal_VOID__VOID</function>. Its name follows
1314 a simple convention which encodes the function parameter and return value
1315 types in the function name. Specifically, the value in front of the
1316 double underscore is the type of the return value, while the value(s)
1317 after the double underscore denote the parameter types.
1321 The header <filename>gobject/gmarshal.h</filename> defines a set of
1322 commonly needed closures that one can use. If you want to have complex
1323 marshallers for your signals you should probably use glib-genmarshal
1324 to autogenerate them from a file containing their return and
1330 this is utterly wrong and should be completely removed - or rewritten
1331 with a better example than writing a buffer using synchronous signals.
1334 <title>How to provide more flexibility to users?</title>
1337 The previous implementation does the job but the signal facility of
1338 GObject can be used to provide even more flexibility to this file
1339 change notification mechanism. One of the key ideas is to make the
1340 process of writing data to the file part of the signal emission
1341 process to allow users to be notified either before or after the
1342 data is written to the file.
1346 To integrate the process of writing the data to the file into the
1347 signal emission mechanism, we can register a default class closure
1348 for this signal which will be invoked during the signal emission,
1349 just like any other user-connected signal handler.
1353 The first step to implement this idea is to change the signature of
1354 the signal: we need to pass around the buffer to write and its size.
1355 To do this, we use our own marshaller which will be generated
1356 through GLib's glib-genmarshal tool. We thus create a file named <filename>marshall.list</filename> which contains
1357 the following single line:
1361 and use the Makefile provided in <filename>sample/signal/Makefile</filename> to generate the file named
1362 <filename>maman-file-complex-marshall.c</filename>. This C file is finally included in
1363 <filename>maman-file-complex.c</filename>.
1367 Once the marshaller is present, we register the signal and its marshaller in the class_init function
1368 of the object <type>MamanFileComplex</type> (full source for this object is included in
1369 <filename>sample/signal/maman-file-complex.{h|c}</filename>):
1371 GClosure *default_closure;
1372 GType param_types[2];
1374 default_closure = g_cclosure_new (G_CALLBACK (default_write_signal_handler),
1375 (gpointer)0xdeadbeaf /* user_data */,
1376 NULL /* destroy_data */);
1378 param_types[0] = G_TYPE_POINTER;
1379 param_types[1] = G_TYPE_UINT;
1380 klass->write_signal_id =
1381 g_signal_newv ("write",
1382 G_TYPE_FROM_CLASS (g_class),
1383 G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS,
1384 default_closure /* class closure */,
1385 NULL /* accumulator */,
1386 NULL /* accu_data */,
1387 maman_file_complex_VOID__POINTER_UINT,
1388 G_TYPE_NONE /* return_type */,
1390 param_types /* param_types */);
1392 The code shown above first creates the closure which contains the code to complete the file write. This
1393 closure is registered as the default class_closure of the newly created signal.
1397 Of course, you need to implement completely the code for the default closure since I just provided
1401 default_write_signal_handler (GObject *obj, guint8 *buffer, guint size, gpointer user_data)
1403 g_assert (user_data == (gpointer)0xdeadbeaf);
1404 /* Here, we trigger the real file write. */
1405 g_print ("default signal handler: 0x%x %u\n", buffer, size);
1411 Finally, the client code must invoke the <function>maman_file_complex_write</function> function which
1412 triggers the signal emission:
1414 void maman_file_complex_write (MamanFileComplex *self, guint8 *buffer, guint size)
1417 g_signal_emit (self,
1418 MAMAN_FILE_COMPLEX_GET_CLASS (self)->write_signal_id,
1426 The client code (as shown in <filename>sample/signal/test.c</filename> and below) can now connect signal handlers before
1427 and after the file write is completed: since the default signal handler which does the write itself runs during the
1428 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>
1429 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
1430 which emits signals, I would thus urge you to create all your signals with the G_SIGNAL_RUN_LAST such that your users
1431 have a maximum of flexibility as to when to get the event. Here, we combined it with G_SIGNAL_NO_RECURSE and
1432 G_SIGNAL_NO_HOOKS to ensure our users will not try to do really weird things with our GObject. I strongly advise you
1433 to do the same unless you really know why (in which case you really know the inner workings of GSignal by heart and
1434 you are not reading this).
1439 static void complex_write_event_before (GObject *file, guint8 *buffer, guint size, gpointer user_data)
1441 g_assert (user_data == NULL);
1442 g_print ("Complex Write event before: 0x%x, %u\n", buffer, size);
1445 static void complex_write_event_after (GObject *file, guint8 *buffer, guint size, gpointer user_data)
1447 g_assert (user_data == NULL);
1448 g_print ("Complex Write event after: 0x%x, %u\n", buffer, size);
1451 static void test_file_complex (void)
1456 file = g_object_new (MAMAN_FILE_COMPLEX_TYPE, NULL);
1458 g_signal_connect (G_OBJECT (file), "write",
1459 (GCallback)complex_write_event_before,
1462 g_signal_connect_after (G_OBJECT (file), "write",
1463 (GCallback)complex_write_event_after,
1466 maman_file_complex_write (MAMAN_FILE_COMPLEX (file), buffer, 50);
1468 g_object_unref (G_OBJECT (file));
1471 The code above generates the following output on my machine:
1473 Complex Write event before: 0xbfffe280, 50
1474 default signal handler: 0xbfffe280 50
1475 Complex Write event after: 0xbfffe280, 50
1482 this is also utterly wrong on so many levels that I don't even want
1483 to enumerate them. it's also full of completely irrelevant footnotes
1484 about personal preferences demonstrating a severe lack of whatsoever
1485 clue. the whole idea of storing the signal ids inside the Class
1486 structure is so fundamentally flawed that I'll require a frontal
1487 lobotomy just to forget I've ever seen it.
1490 <title>How most people do the same thing with less code</title>
1492 <para>For many historic reasons related to how the ancestor of GObject used to work in GTK+ 1.x versions,
1493 there is a much <emphasis>simpler</emphasis>
1495 <para>I personally think that this method is horribly mind-twisting: it adds a new indirection
1496 which unnecessarily complicates the overall code path. However, because this method is widely used
1497 by all of GTK+ and GObject code, readers need to understand it. The reason why this is done that way
1498 in most of GTK+ is related to the fact that the ancestor of GObject did not provide any other way to
1499 create a signal with a default handler than this one. Some people have tried to justify that it is done
1500 that way because it is better, faster (I am extremely doubtful about the faster bit. As a matter of fact,
1501 the better bit also mystifies me ;-). I have the feeling no one really knows and everyone does it
1502 because they copy/pasted code from code which did the same. It is probably better to leave this
1503 specific trivia to hacker legends domain...
1506 way to create a signal with a default handler than to create
1507 a closure by hand and to use the <function><link linkend="g-signal-newv">g_signal_newv</link></function>.
1510 <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
1511 handler which is stored in the class structure of the object. More specifically, the class structure
1512 contains a function pointer which is accessed during signal emission to invoke the default handler and
1513 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
1514 class structure to the function pointer.
1516 <para>I would like to point out here that the reason why the default handler of a signal is named everywhere
1517 a class_closure is probably related to the fact that it used to be really a function pointer stored in
1518 the class structure.
1523 <para>The following code shows the declaration of the <type>MamanFileSimple</type> class structure which contains
1524 the <function>write</function> function pointer.
1526 struct _MamanFileSimpleClass {
1527 GObjectClass parent;
1529 guint write_signal_id;
1531 /* signal default handlers */
1532 void (*write) (MamanFileSimple *self, guint8 *buffer, guint size);
1535 The <function>write</function> function pointer is initialized in the class_init function of the object
1536 to <function>default_write_signal_handler</function>:
1539 maman_file_simple_class_init (gpointer g_class,
1540 gpointer g_class_data)
1542 GObjectClass *gobject_class = G_OBJECT_CLASS (g_class);
1543 MamanFileSimpleClass *klass = MAMAN_FILE_SIMPLE_CLASS (g_class);
1545 klass->write = default_write_signal_handler;
1547 Finally, the signal is created with <function><link linkend="g-signal-new">g_signal_new</link></function> in the same class_init function:
1549 klass->write_signal_id =
1550 g_signal_new ("write",
1551 G_TYPE_FROM_CLASS (g_class),
1552 G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS,
1553 G_STRUCT_OFFSET (MamanFileSimpleClass, write),
1554 NULL /* accumulator */,
1555 NULL /* accu_data */,
1556 maman_file_complex_VOID__POINTER_UINT,
1557 G_TYPE_NONE /* return_type */,
1562 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>
1563 macro which indicates the offset of the member <emphasis>write</emphasis> from the start of the
1564 <type>MamanFileSimpleClass</type> class structure.
1566 <para>GSignal uses this offset to create a special wrapper closure
1567 which first retrieves the target function pointer before calling it.
1573 While the complete code for this type of default handler looks less cluttered as shown in
1574 <filename>sample/signal/maman-file-simple.{h|c}</filename>, it contains numerous subtleties.
1575 The main subtle point which everyone must be aware of is that the signature of the default
1576 handler created that way does not have a user_data argument:
1577 <function>default_write_signal_handler</function> is different in
1578 <filename>sample/signal/maman-file-complex.c</filename> and in
1579 <filename>sample/signal/maman-file-simple.c</filename>.
1582 <para>If you have doubts about which method to use, I would advise you to use the second one which
1583 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>:
1584 it is better to write code which looks like the vast majority of other GTK+/GObject code than to
1585 do it your own way. However, now, you know why.
1594 yet another pointless section. if we are scared of possible abuses
1595 from the users then we should not be mentioning it inside a tutorial
1596 for beginners. but, obviously, there's nothing to be afraid of - it's
1597 just that this section must be completely reworded.
1600 <title>How users can abuse signals (and why some think it is good)</title>
1602 <para>Now that you know how to create signals to which the users can connect easily and at any point in
1603 the signal emission process thanks to <function><link linkend="g-signal-connect">g_signal_connect</link></function>,
1604 <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
1605 users can and will screw you. This is also interesting to know how you too, can screw other people.
1606 This will make you feel good and eleet.
1612 <listitem><para>stop the emission of the signal at anytime</para></listitem>
1613 <listitem><para>override the default handler of the signal if it is stored as a function
1614 pointer in the class structure (which is the preferred way to create a default signal handler,
1615 as discussed in the previous section).</para></listitem>
1620 In both cases, the original programmer should be as careful as possible to write code which is
1621 resistant to the fact that the default handler of the signal might not able to run. This is obviously
1622 not the case in the example used in the previous sections since the write to the file depends on whether
1623 or not the default handler runs (however, this might be your goal: to allow the user to prevent the file
1624 write if he wishes to).
1628 If all you want to do is to stop the signal emission from one of the callbacks you connected yourself,
1629 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
1634 If the signal's default handler is just a class function pointer, it is also possible to override
1635 it yourself from the class_init function of a type which derives from the parent. That way, when the signal
1636 is emitted, the parent class will use the function provided by the child as a signal default handler.
1637 Of course, it is also possible (and recommended) to chain up from the child to the parent's default signal
1638 handler to ensure the integrity of the parent object.
1642 Overriding a class method and chaining up was demonstrated in <xref linkend="howto-gobject-methods"/>
1643 which is why I won't bother to show exactly how to do it here again.
1654 <title>Warning on signal creation and default closure</title>
1657 Most of the existing code I have seen up to now (in both GTK+, GNOME libraries and
1658 many GTK+ and GNOME applications) using signals uses a small
1659 variation of the default handler pattern I have shown in the previous section.
1663 Usually, the <function><link linkend="g-signal-new">g_signal_new</link></function> function is preferred over
1664 <function><link linkend="g-signal-newv">g_signal_newv</link></function>. When <function><link linkend="g-signal-new">g_signal_new</link></function>
1665 is used, the default closure is exported as a class function. For example,
1666 <filename>gobject.h</filename> contains the declaration of <link linkend="GObjectClass"><type>GObjectClass</type></link>
1667 whose notify class function is the default handler for the <emphasis>notify</emphasis>
1670 struct _GObjectClass
1672 GTypeClass g_type_class;
1674 /* class methods and other stuff. */
1677 void (*notify) (GObject *object,
1684 <filename>gobject.c</filename>'s <function><link linkend="g-object-do-class-init">g_object_do_class_init</link></function> function
1685 registers the <emphasis>notify</emphasis> signal and initializes this class function
1689 g_object_do_class_init (GObjectClass *class)
1694 class->notify = NULL;
1696 gobject_signals[NOTIFY] =
1697 g_signal_new ("notify",
1698 G_TYPE_FROM_CLASS (class),
1699 G_SIGNAL_RUN_FIRST | G_SIGNAL_NO_RECURSE | G_SIGNAL_DETAILED | G_SIGNAL_NO_HOOKS,
1700 G_STRUCT_OFFSET (GObjectClass, notify),
1702 g_cclosure_marshal_VOID__PARAM,
1707 <function><link linkend="g-signal-new">g_signal_new</link></function> creates a <link linkend="GClosure"><type>GClosure</type></link> which dereferences the
1708 type's class structure to access the class function pointer and invoke it if it not NULL. The
1709 class function is ignored it is set to NULL.
1713 To understand the reason for such a complex scheme to access the signal's default handler,
1714 you must remember the whole reason for the use of these signals. The goal here is to delegate
1715 a part of the process to the user without requiring the user to subclass the object to override
1716 one of the class functions. The alternative to subclassing, that is, the use of signals
1717 to delegate processing to the user, is, however, a bit less optimal in terms of speed: rather
1718 than just dereferencing a function pointer in a class structure, you must start the whole
1719 process of signal emission which is a bit heavyweight.
1723 This is why some people decided to use class functions for some signal's default handlers:
1724 rather than having users connect a handler to the signal and stop the signal emission
1725 from within that handler, you just need to override the default class function which is
1726 supposedly more efficient.