1 <?xml version='1.0' encoding="ISO-8859-1"?>
4 This chapter tries to answer the real-life questions of users and presents
5 the most common scenario use cases I could come up with.
6 The use cases are presented from most likely to less likely.
10 <chapter id="howto-gobject">
11 <title>How to define and implement a new GObject</title>
14 Clearly, this is one of the most common questions people ask: they just want to crank code and
15 implement a subclass of a GObject. Sometimes because they want to create their own class hierarchy,
16 sometimes because they want to subclass one of GTK+'s widget. This chapter will focus on the
17 implementation of a subtype of GObject. The sample source code
18 associated with this section can be found in the documentation's source tarball, in the
19 <filename>sample/gobject</filename> directory:
21 <listitem><para><filename>maman-bar.{h|c}</filename>: this is the source for a object which derives from
22 <type><link linkend="GObject">GObject</link></type> and which shows how to declare different types of methods on the object.
24 <listitem><para><filename>maman-subbar.{h|c}</filename>: this is the source for a object which derives from
25 <type>MamanBar</type> and which shows how to override some of its parent's methods.
27 <listitem><para><filename>maman-foo.{h|c}</filename>: this is the source for an object which derives from
28 <type><link linkend="GObject">GObject</link></type> and which declares a signal.
30 <listitem><para><filename>test.c</filename>: this is the main source which instantiates an instance of
31 type and exercises their API.
36 <sect1 id="howto-gobject-header">
37 <title>Boilerplate header code</title>
40 The first step before writing the code for your GObject is to write the type's header which contains
41 the needed type, function and macro definitions. Each of these elements is nothing but a convention
42 which is followed not only by GTK+'s code but also by most users of GObject. If you feel the need
43 not to obey the rules stated below, think about it twice:
45 <listitem><para>If your users are a bit accustomed to GTK+ code or any GLib code, they will
46 be a bit surprised and getting used to the conventions you decided upon will take time (money) and
47 will make them grumpy (not a good thing)
50 You must assess the fact that these conventions might have been designed by both smart
51 and experienced people: maybe they were at least partly right. Try to put your ego aside.
57 Pick a name convention for your headers and source code and stick to it:
60 use a dash to separate the prefix from the typename: <filename>maman-bar.h</filename> and
61 <filename>maman-bar.c</filename> (this is the convention used by Nautilus and most GNOME libraries).
64 use an underscore to separate the prefix from the typename: <filename>maman_bar.h</filename> and
65 <filename>maman_bar.c</filename>.
68 Do not separate the prefix from the typename: <filename>mamanbar.h</filename> and
69 <filename>mamanbar.c</filename>. (this is the convention used by GTK+)
72 I personally like the first solution better: it makes reading file names easier for those with poor
77 When you need some private (internal) declarations in several (sub)classes,
78 you can define them in a private header file which is often named by
79 appending the <emphasis>private</emphasis> keyword to the public header name.
80 For example, one could use <filename>maman-bar-private.h</filename>,
81 <filename>maman_bar_private.h</filename> or <filename>mamanbarprivate.h</filename>.
82 Typically, such private header files are not installed.
86 The basic conventions for any header which exposes a GType are described in
87 <xref linkend="gtype-conventions"/>. Most GObject-based code also obeys one of of the following
88 conventions: pick one and stick to it.
91 If you want to declare a type named bar with prefix maman, name the type instance
92 <function>MamanBar</function> and its class <function>MamanBarClass</function>
93 (name is case-sensitive). It is customary to declare them with code similar to the
97 * Copyright/Licensing information.
104 * Potentially, include other headers on which this header depends.
111 typedef struct _MamanBar MamanBar;
112 typedef struct _MamanBarClass MamanBarClass;
116 /* instance members */
119 struct _MamanBarClass {
124 /* used by MAMAN_TYPE_BAR */
125 GType maman_bar_get_type (void);
128 * Method definitions.
135 Most GTK+ types declare their private fields in the public header with a /* private */ comment,
136 relying on their user's intelligence not to try to play with these fields. Fields not marked private
137 are considered public by default. The /* protected */ comment (same semantics as those of C++)
138 is also used, mainly in the GType library, in code written by Tim Janik.
143 /*< private >*/
149 All of Nautilus code and a lot of GNOME libraries use private indirection members, as described
150 by Herb Sutter in his Pimpl articles
151 (see <ulink url="http://www.gotw.ca/gotw/024.htm">Compilation Firewalls</ulink>
152 and <ulink url="http://www.gotw.ca/gotw/028.htm">The Fast Pimpl Idiom</ulink>
153 : he summarizes the different issues better than I will).
155 typedef struct _MamanBarPrivate MamanBarPrivate;
159 /*< private >*/
160 MamanBarPrivate *priv;
163 <note><simpara>Do not call this <varname>private</varname>, as that is a registered c++ keyword.</simpara></note>
164 The private structure is then defined in the .c file, instantiated in the object's
165 <function>init</function> function and destroyed in the object's <function>finalize</function> function.
168 maman_bar_finalize (GObject *object) {
169 MamanBar *self = MAMAN_BAR (object);
175 maman_bar_init (GTypeInstance *instance, gpointer g_class) {
176 MamanBar *self = MAMAN_BAR (instance);
177 self->priv = g_new0 (MamanBarPrivate,1);
184 A similar alternative, available since GLib version 2.4, is to define a private structure in the .c file,
185 declare it as a private structure in <function>maman_bar_class_init</function> using
186 <function><link linkend="g-type-class-add-private">g_type_class_add_private</link></function>.
187 Instead of allocating memory in <function>maman_bar_init</function> a pointer to the private memory area is
188 stored in the instance to allow convenient access to this structure.
189 A private structure will then be attached to each newly created object by the GObject system.
190 You don't need to free or allocate the private structure, only the objects or pointers that it may contain.
191 Another advantage of this to the previous version is that is lessens memory fragmentation,
192 as the public and private parts of the instance memory are allocated at once.
194 typedef struct _MamanBarPrivate MamanBarPrivate;
196 struct _MamanBarPrivate {
201 maman_bar_class_init (MamanBarClass *klass)
204 g_type_class_add_private (klass, sizeof (MamanBarPrivate));
209 maman_bar_init (GTypeInstance *instance, gpointer g_class) {
210 MamanBar *self = MAMAN_BAR (instance);
211 self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, MAMAN_TYPE_BAR, MamanBarPrivate);
221 Finally, there are different header include conventions. Again, pick one and stick to it. I personally
222 use indifferently any of the two, depending on the codebase I work on: the rule is consistency.
225 Some people add at the top of their headers a number of #include directives to pull in
226 all the headers needed to compile client code. This allows client code to simply
227 #include "maman-bar.h".
230 Other do not #include anything and expect the client to #include themselves the headers
231 they need before including your header. This speeds up compilation because it minimizes the
232 amount of pre-processor work. This can be used in conjunction with the re-declaration of certain
233 unused types in the client code to minimize compile-time dependencies and thus speed up
241 <sect1 id="howto-gobject-code">
242 <title>Boilerplate code</title>
245 In your code, the first step is to #include the needed headers: depending on your header include strategy, this
246 can be as simple as #include "maman-bar.h" or as complicated as tens of #include lines ending with
247 #include "maman-bar.h":
250 * Copyright information
253 #include "maman-bar.h"
255 /* If you use Pimpls, include the private structure
256 * definition here. Some people create a maman-bar-private.h header
257 * which is included by the maman-bar.c file and which contains the
258 * definition for this private structure.
260 struct _MamanBarPrivate {
266 * forward definitions
272 Implement <function>maman_bar_get_type</function> and make sure the code compiles:
275 maman_bar_get_type (void)
277 static GType type = 0;
279 static const GTypeInfo info = {
280 sizeof (MamanBarClass),
281 NULL, /* base_init */
282 NULL, /* base_finalize */
283 NULL, /* class_init */
284 NULL, /* class_finalize */
285 NULL, /* class_data */
288 NULL /* instance_init */
290 type = g_type_register_static (G_TYPE_OBJECT,
300 <sect1 id="howto-gobject-construction">
301 <title>Object Construction</title>
304 People often get confused when trying to construct their GObjects because of the
305 sheer number of different ways to hook into the objects's construction process: it is
306 difficult to figure which is the <emphasis>correct</emphasis>, recommended way.
310 <xref linkend="gobject-construction-table"/> shows what user-provided functions
311 are invoked during object instantiation and in which order they are invoked.
312 A user looking for the equivalent of the simple C++ constructor function should use
313 the instance_init method. It will be invoked after all the parent's instance_init
314 functions have been invoked. It cannot take arbitrary construction parameters
315 (as in C++) but if your object needs arbitrary parameters to complete initialization,
316 you can use construction properties.
320 Construction properties will be set only after all instance_init functions have run.
321 No object reference will be returned to the client of <function><link linkend="g-object-new>">g_object_new></link></function>
322 until all the construction properties have been set.
326 As such, I would recommend writing the following code first:
329 maman_bar_init (GTypeInstance *instance,
332 MamanBar *self = (MamanBar *)instance;
333 self->private = g_new0 (MamanBarPrivate, 1);
335 /* initialize all public and private members to reasonable default values. */
336 /* If you need specific construction properties to complete initialization,
337 * delay initialization completion until the property is set.
341 And make sure that you set <function>maman_bar_init</function> as the type's instance_init function
342 in <function>maman_bar_get_type</function>. Make sure the code builds and runs: create an instance
343 of the object and make sure <function>maman_bar_init</function> is called (add a
344 <function><link linkend="g-print">g_print</link></function> call in it).
348 Now, if you need special construction properties, install the properties in the class_init function,
349 override the set and get methods and implement the get and set methods as described in
350 <xref linkend="gobject-properties"/>. Make sure that these properties use a construct only
351 <type><link linkend="GParamSpec">GParamSpec</link></type> by setting the param spec's flag field to G_PARAM_CONSTRUCT_ONLY: this helps
352 GType ensure that these properties are not set again later by malicious user code.
355 bar_class_init (MamanBarClass *klass)
357 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
358 GParamSpec *maman_param_spec;
360 gobject_class->set_property = bar_set_property;
361 gobject_class->get_property = bar_get_property;
363 maman_param_spec = g_param_spec_string ("maman",
364 "Maman construct prop",
366 "no-name-set" /* default value */,
367 G_PARAM_CONSTRUCT_ONLY |G_PARAM_READWRITE);
369 g_object_class_install_property (gobject_class,
374 If you need this, make sure you can build and run code similar to the code shown above. Make sure
375 your construct properties can set correctly during construction, make sure you cannot set them
376 afterwards and make sure that if your users do not call <function><link linkend="g-object-new">g_object_new</link></function>
377 with the required construction properties, these will be initialized with the default values.
381 I consider good taste to halt program execution if a construction property is set its
382 default value. This allows you to catch client code which does not give a reasonable
383 value to the construction properties. Of course, you are free to disagree but you
384 should have a good reason to do so.
387 <para>Some people sometimes need to construct their object but only after the construction properties
388 have been set. This is possible through the use of the constructor class method as described in
389 <xref linkend="gobject-instantiation"/>. However, I have yet to see <emphasis>any</emphasis> reasonable
390 use of this feature. As such, to initialize your object instances, use by default the base_init function
391 and construction properties.
395 <sect1 id="howto-gobject-destruction">
396 <title>Object Destruction</title>
399 Again, it is often difficult to figure out which mechanism to use to hook into the object's
400 destruction process: when the last <function><link linkend="g-object-unref">g_object_unref</link></function> function call is made,
401 a lot of things happen as described in <xref linkend="gobject-destruction-table"/>.
405 The destruction process of your object must be split is two different phases: you must override
406 both the dispose and the finalize class methods.
408 struct _MamanBarPrivate {
409 gboolean dispose_has_run;
412 static GObjectClass *parent_class = NULL;
415 bar_dispose (GObject *obj)
417 MamanBar *self = (MamanBar *)obj;
419 if (self->priv->dispose_has_run) {
420 /* If dispose did already run, return. */
423 /* Make sure dispose does not run twice. */
424 object->priv->dispose_has_run = TRUE;
427 * In dispose, you are supposed to free all types referenced from this
428 * object which might themselves hold a reference to self. Generally,
429 * the most simple solution is to unref all members on which you own a
433 /* Chain up to the parent class */
434 G_OBJECT_CLASS (parent_class)->dispose (obj);
438 bar_finalize (GObject *obj)
440 MamanBar *self = (MamanBar *)obj;
442 /* Chain up to the parent class */
443 G_OBJECT_CLASS (parent_class)->finalize (obj);
447 bar_class_init (BarClass *klass)
449 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
451 gobject_class->dispose = bar_dispose;
452 gobject_class->finalize = bar_finalize;
454 parent_class = g_type_class_peek_parent (klass);
455 g_type_class_add_private(klass,sizeof(MamanBarPrivate));
459 maman_bar_init (GTypeInstance *instance,
462 MamanBar *self = (MamanBar *)instance;
463 self->priv = G_TYPE_INSTANCE_GET_PRIVATE(self, BT_TYPE_PATTERN, BtPatternPrivate);
464 self->priv->dispose_has_run = FALSE;
471 Add similar code to your GObject, make sure the code still builds and runs: dispose and finalize must be called
472 during the last unref.
473 It is possible that object methods might be invoked after dispose is run and before finalize runs. GObject
474 does not consider this to be a program error: you must gracefully detect this and neither crash nor warn
475 the user. To do this, you need something like the following code at the start of each object method, to make
476 sure the object's data is still valid before manipulating it:
478 if (self->private->dispose_has_run) {
479 /* Dispose has run. Data is not valid anymore. */
486 <sect1 id="howto-gobject-methods">
487 <title>Object methods</title>
490 Just as with C++, there are many different ways to define object
491 methods and extend them: the following list and sections draw on C++ vocabulary.
492 (Readers are expected to know basic C++ buzzwords. Those who have not had to
493 write C++ code recently can refer to e.g. <ulink url="http://www.cplusplus.com/doc/tutorial/"/> to refresh their
497 non-virtual public methods,
500 virtual public methods and
503 virtual private methods
509 <title>Non-virtual public methods</title>
512 These are the simplest: you want to provide a simple method which can act on your object. All you need
513 to do is to provide a function prototype in the header and an implementation of that prototype
516 /* declaration in the header. */
517 void maman_bar_do_action (MamanBar *self, /* parameters */);
518 /* implementation in the source file */
519 void maman_bar_do_action (MamanBar *self, /* parameters */)
526 <para>There is really nothing scary about this.</para>
530 <title>Virtual public methods</title>
533 This is the preferred way to create polymorphic GObjects. All you need to do is to
534 define the common method and its class function in the public header, implement the
535 common method in the source file and re-implement the class function in each object
536 which inherits from you.
538 /* declaration in maman-bar.h. */
539 struct _MamanBarClass {
543 void (*do_action) (MamanBar *self, /* parameters */);
545 void maman_bar_do_action (MamanBar *self, /* parameters */);
546 /* implementation in maman-bar.c */
547 void maman_bar_do_action (MamanBar *self, /* parameters */)
549 MAMAN_BAR_GET_CLASS (self)->do_action (self, /* parameters */);
552 The code above simply redirects the do_action call to the relevant class function. Some users,
553 concerned about performance, do not provide the <function>maman_bar_do_action</function>
554 wrapper function and require users to dereference the class pointer themselves. This is not such
555 a great idea in terms of encapsulation and makes it difficult to change the object's implementation
556 afterwards, should this be needed.
560 Other users, also concerned by performance issues, declare the <function>maman_bar_do_action</function>
561 function inline in the header file. This, however, makes it difficult to change the
562 object's implementation later (although easier than requiring users to directly dereference the class
563 function) and is often difficult to write in a portable way (the <emphasis>inline</emphasis> keyword
564 is not part of the C standard).
568 In doubt, unless a user shows you hard numbers about the performance cost of the function call,
569 just <function>maman_bar_do_action</function> in the source file.
573 Please, note that it is possible for you to provide a default implementation for this class method in
574 the object's class_init function: initialize the klass->do_action field to a pointer to the actual
575 implementation. You can also make this class method pure virtual by initializing the klass->do_action
579 maman_bar_real_do_action_two (MamanBar *self, /* parameters */)
581 /* Default implementation for the virtual method. */
585 maman_bar_class_init (BarClass *klass)
587 /* pure virtual method: mandates implementation in children. */
588 klass->do_action_one = NULL;
589 /* merely virtual method. */
590 klass->do_action_two = maman_bar_real_do_action_two;
593 void maman_bar_do_action_one (MamanBar *self, /* parameters */)
595 MAMAN_BAR_GET_CLASS (self)->do_action_one (self, /* parameters */);
597 void maman_bar_do_action_two (MamanBar *self, /* parameters */)
599 MAMAN_BAR_GET_CLASS (self)->do_action_two (self, /* parameters */);
606 <title>Virtual private Methods</title>
609 These are very similar to Virtual Public methods. They just don't have a public function to call the
610 function directly. The header file contains only a declaration of the class function:
612 /* declaration in maman-bar.h. */
613 struct _MamanBarClass {
617 void (*helper_do_specific_action) (MamanBar *self, /* parameters */);
619 void maman_bar_do_any_action (MamanBar *self, /* parameters */);
621 These class functions are often used to delegate part of the job to child classes:
623 /* this accessor function is static: it is not exported outside of this file. */
625 maman_bar_do_specific_action (MamanBar *self, /* parameters */)
627 MAMAN_BAR_GET_CLASS (self)->do_specific_action (self, /* parameters */);
630 void maman_bar_do_any_action (MamanBar *self, /* parameters */)
632 /* random code here */
635 * Try to execute the requested action. Maybe the requested action cannot be implemented
636 * here. So, we delegate its implementation to the child class:
638 maman_bar_do_specific_action (self, /* parameters */);
640 /* other random code here */
646 Again, it is possible to provide a default implementation for this private virtual class function:
649 maman_bar_class_init (MamanBarClass *klass)
651 /* pure virtual method: mandates implementation in children. */
652 klass->do_specific_action_one = NULL;
653 /* merely virtual method. */
654 klass->do_specific_action_two = maman_bar_real_do_specific_action_two;
660 Children can then implement the subclass with code such as:
663 maman_bar_subtype_class_init (MamanBarSubTypeClass *klass)
665 MamanBarClass *bar_class = MAMAN_BAR_CLASS (klass);
666 /* implement pure virtual class function. */
667 bar_class->do_specific_action_one = maman_bar_subtype_do_specific_action_one;
674 <sect1 id="howto-gobject-chainup">
675 <title>Chaining up</title>
677 <para>Chaining up is often loosely defined by the following set of conditions:
679 <listitem><para>Parent class A defines a public virtual method named <function>foo</function> and
680 provides a default implementation.</para></listitem>
681 <listitem><para>Child class B re-implements method <function>foo</function>.</para></listitem>
682 <listitem><para>In the method B::foo, the child class B calls its parent class method A::foo.</para></listitem>
684 There are many uses to this idiom:
686 <listitem><para>You need to change the behaviour of a class without modifying its code. You create
687 a subclass to inherit its implementation, re-implement a public virtual method to modify the behaviour
688 slightly and chain up to ensure that the previous behaviour is not really modified, just extended.
690 <listitem><para>You are lazy, you have access to the source code of the parent class but you don't want
691 to modify it to add method calls to new specialized method calls: it is faster to hack the child class
692 to chain up than to modify the parent to call down.</para></listitem>
693 <listitem><para>You need to implement the Chain Of Responsibility pattern: each object of the inheritance
694 tree chains up to its parent (typically, at the beginning or the end of the method) to ensure that
695 they each handler is run in turn.</para></listitem>
697 I am personally not really convinced any of the last two uses are really a good idea but since this
698 programming idiom is often used, this section attempts to explain how to implement it.
702 To explicitly chain up to the implementation of the virtual method in the parent class,
703 you first need a handle to the original parent class structure. This pointer can then be used to
704 access the original class function pointer and invoke it directly.
707 The <emphasis>original</emphasis> adjective used in this sentence is not innocuous. To fully
708 understand its meaning, you need to recall how class structures are initialized: for each object type,
709 the class structure associated to this object is created by first copying the class structure of its
710 parent type (a simple <function>memcpy</function>) and then by invoking the class_init callback on
711 the resulting class structure. Since the class_init callback is responsible for overwriting the class structure
712 with the user re-implementations of the class methods, we cannot merely use the modified copy of the parent class
713 structure stored in our derived instance. We want to get a copy of the class structure of an instance of the parent
719 <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
720 class structure. Its input is a pointer to the class of the derived object and it returns a pointer
721 to the original parent class structure. The code below shows how you could use it:
724 b_method_to_call (B *obj, int a)
727 AClass *parent_class;
728 klass = B_GET_CLASS (obj);
729 parent_class = g_type_class_peek_parent (klass);
731 /* do stuff before chain up */
732 parent_class->method_to_call (obj, a);
733 /* do stuff after chain up */
736 A lot of people who use this idiom in GTK+ store the parent class structure pointer in a global static
737 variable to avoid the costly call to <function><link linkend="g-type-class-peek-parent">g_type_class_peek_parent</link></function> for each function call.
738 Typically, the class_init callback initializes the global static variable. <filename>gtk/gtkhscale.c</filename>
745 <!-- End Howto GObject -->
748 <chapter id="howto-interface">
749 <title>How to define and implement interfaces</title>
751 <sect1 id="howto-interface-define">
752 <title>How to define interfaces</title>
755 The bulk of interface definition has already been shown in <xref linkend="gtype-non-instantiable-classed"/>
756 but I feel it is needed to show exactly how to create an interface. The sample source code
757 associated to this section can be found in the documentation's source tarball, in the
758 <filename>sample/interface/maman-ibaz.{h|c}</filename> file.
762 As above, the first step is to get the header right:
767 #include <glib-object.h>
769 #define MAMAN_TYPE_IBAZ (maman_ibaz_get_type ())
770 #define MAMAN_IBAZ(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_TYPE_IBAZ, MamanIbaz))
771 #define MAMAN_IS_IBAZ(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_TYPE_IBAZ))
772 #define MAMAN_IBAZ_GET_INTERFACE(inst) (G_TYPE_INSTANCE_GET_INTERFACE ((inst), MAMAN_TYPE_IBAZ, MamanIbazInterface))
775 typedef struct _MamanIbaz MamanIbaz; /* dummy object */
776 typedef struct _MamanIbazInterface MamanIbazInterface;
778 struct _MamanIbazInterface {
779 GTypeInterface parent;
781 void (*do_action) (MamanIbaz *self);
784 GType maman_ibaz_get_type (void);
786 void maman_ibaz_do_action (MamanIbaz *self);
788 #endif /*MAMAN_IBAZ_H*/
790 This code is the same as the code for a normal <type><link linkend="GType">GType</link></type>
791 which derives from a <type><link linkend="GObject">GObject</link></type> except for a few details:
794 The <function>_GET_CLASS</function> macro is called <function>_GET_INTERFACE</function>
795 and not implemented with <function><link linkend="G_TYPE_INSTANCE_GET_CLASS">G_TYPE_INSTANCE_GET_CLASS</link></function>
796 but with <function><link linkend="G_TYPE_INSTANCE_GET_INTERFACE">G_TYPE_INSTANCE_GET_INTERFACE</link></function>.
799 The instance type, <type>MamanIbaz</type> is not fully defined: it is used merely as an abstract
800 type which represents an instance of whatever object which implements the interface.
806 The implementation of the <type>MamanIbaz</type> type itself is trivial:
808 <listitem><para><function>maman_ibaz_get_type</function> registers the
809 type in the type system.
811 <listitem><para><function>maman_ibaz_base_init</function> is expected
812 to register the interface's signals if there are any (we will see a bit
813 (later how to use them). Make sure to use a static local boolean variable
814 to make sure not to run the initialization code twice (as described in
815 <xref linkend="gtype-non-instantiable-classed-init"/>,
816 <function>base_init</function> is run once for each interface implementation
817 instantiation)</para></listitem>
818 <listitem><para><function>maman_ibaz_do_action</function> dereferences the class
819 structure to access its associated class function and calls it.
824 maman_ibaz_base_init (gpointer g_class)
826 static gboolean initialized = FALSE;
829 /* create interface signals here. */
835 maman_ibaz_get_type (void)
837 static GType type = 0;
839 static const GTypeInfo info = {
840 sizeof (MamanIbazInterface),
841 maman_ibaz_base_init, /* base_init */
842 NULL, /* base_finalize */
843 NULL, /* class_init */
844 NULL, /* class_finalize */
845 NULL, /* class_data */
848 NULL /* instance_init */
850 type = g_type_register_static (G_TYPE_INTERFACE, "MamanIbaz", &info, 0);
855 void maman_ibaz_do_action (MamanIbaz *self)
857 MAMAN_IBAZ_GET_INTERFACE (self)->do_action (self);
863 <sect1 id="howto-interface-implement">
864 <title>How To define implement an Interface?</title>
867 Once the interface is defined, implementing it is rather trivial. Source code showing how to do this
868 for the <type>IBaz</type> interface defined in the previous section is located in
869 <filename>sample/interface/maman-baz.{h|c}</filename>.
873 The first step is to define a normal GType. Here, we have decided to use a GType which derives from
874 GObject. Its name is <type>MamanBaz</type>:
879 #include <glib-object.h>
881 #define MAMAN_TYPE_BAZ (maman_baz_get_type ())
882 #define MAMAN_BAZ(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_TYPE_BAZ, Mamanbaz))
883 #define MAMAN_BAZ_CLASS(vtable) (G_TYPE_CHECK_CLASS_CAST ((vtable), MAMAN_TYPE_BAZ, MamanbazClass))
884 #define MAMAN_IS_BAZ(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_TYPE_BAZ))
885 #define MAMAN_IS_BAZ_CLASS(vtable) (G_TYPE_CHECK_CLASS_TYPE ((vtable), MAMAN_TYPE_BAZ))
886 #define MAMAN_BAZ_GET_CLASS(inst) (G_TYPE_INSTANCE_GET_CLASS ((inst), MAMAN_TYPE_BAZ, MamanbazClass))
889 typedef struct _MamanBaz MamanBaz;
890 typedef struct _MamanBazClass MamanBazClass;
897 struct _MamanBazClass {
901 GType maman_baz_get_type (void);
906 There is clearly nothing specifically weird or scary about this header: it does not define any weird API
907 or derives from a weird type.
911 The second step is to implement <function>maman_baz_get_type</function>:
914 maman_baz_get_type (void)
916 static GType type = 0;
918 static const GTypeInfo info = {
919 sizeof (MamanBazClass),
920 NULL, /* base_init */
921 NULL, /* base_finalize */
922 NULL, /* class_init */
923 NULL, /* class_finalize */
924 NULL, /* class_data */
927 baz_instance_init /* instance_init */
929 static const GInterfaceInfo ibaz_info = {
930 (GInterfaceInitFunc) baz_interface_init, /* interface_init */
931 NULL, /* interface_finalize */
932 NULL /* interface_data */
934 type = g_type_register_static (G_TYPE_OBJECT,
937 g_type_add_interface_static (type,
944 This function is very much like all the similar functions we looked at previously. The only interface-specific
945 code present here is the call to <function><link linkend="g-type-add-interface-static">g_type_add_interface_static</link></function> which is used to inform
946 the type system that this just-registered <type><link linkend="GType">GType</link></type> also implements the interface
947 <function>MAMAN_TYPE_IBAZ</function>.
951 <function>baz_interface_init</function>, the interface initialization function, is also pretty simple:
953 static void baz_do_action (MamanBaz *self)
955 g_print ("Baz implementation of IBaz interface Action: 0x%x.\n", self->instance_member);
958 baz_interface_init (gpointer g_iface,
961 MamanIbazInteface *iface = (MamanIbazInteface *)g_iface;
962 iface->do_action = (void (*) (MamanIbaz *self))baz_do_action;
965 baz_instance_init (GTypeInstance *instance,
968 MamanBaz *self = MAMAN_BAZ(instance);
969 self->instance_member = 0xdeadbeaf;
972 <function>baz_interface_init</function> merely initializes the interface methods to the implementations
973 defined by <type>MamanBaz</type>: <function>maman_baz_do_action</function> does nothing very useful
980 <title>Interface definition prerequisites</title>
983 To specify that an interface requires the presence of other interfaces when implemented,
984 GObject introduces the concept of <emphasis>prerequisites</emphasis>: it is possible to associate
985 a list of prerequisite interfaces to an interface. For example, if object A wishes to implement interface
986 I1, and if interface I1 has a prerequisite on interface I2, A has to implement both I1 and I2.
990 The mechanism described above is, in practice, very similar to Java's interface I1 extends
991 interface I2. The example below shows the GObject equivalent:
994 type = g_type_register_static (G_TYPE_INTERFACE, "MamanIbar", &info, 0);
995 /* Make the MamanIbar interface require MamanIbaz interface. */
996 g_type_interface_add_prerequisite (type, MAMAN_TYPE_IBAZ);
998 The code shown above adds the MamanIbaz interface to the list of prerequisites of MamanIbar while the
999 code below shows how an implementation can implement both interfaces and register their implementations:
1001 static void ibar_do_another_action (MamanBar *self)
1003 g_print ("Bar implementation of IBar interface Another Action: 0x%x.\n", self->instance_member);
1007 ibar_interface_init (gpointer g_iface,
1008 gpointer iface_data)
1010 MamanIbarInterface *iface = (MamanIbarInterface *)g_iface;
1011 iface->do_another_action = (void (*) (MamanIbar *self))ibar_do_another_action;
1015 static void ibaz_do_action (MamanBar *self)
1017 g_print ("Bar implementation of IBaz interface Action: 0x%x.\n", self->instance_member);
1021 ibaz_interface_init (gpointer g_iface,
1022 gpointer iface_data)
1024 MamanIbazInterface *iface = (MamanIbazInterface *)g_iface;
1025 iface->do_action = (void (*) (MamanIbaz *self))ibaz_do_action;
1029 bar_instance_init (GTypeInstance *instance,
1032 MamanBar *self = (MamanBar *)instance;
1033 self->instance_member = 0x666;
1037 maman_bar_get_type (void)
1039 static GType type = 0;
1041 static const GTypeInfo info = {
1042 sizeof (MamanBarClass),
1043 NULL, /* base_init */
1044 NULL, /* base_finalize */
1045 NULL, /* class_init */
1046 NULL, /* class_finalize */
1047 NULL, /* class_data */
1049 0, /* n_preallocs */
1050 bar_instance_init /* instance_init */
1052 static const GInterfaceInfo ibar_info = {
1053 (GInterfaceInitFunc) ibar_interface_init, /* interface_init */
1054 NULL, /* interface_finalize */
1055 NULL /* interface_data */
1057 static const GInterfaceInfo ibaz_info = {
1058 (GInterfaceInitFunc) ibaz_interface_init, /* interface_init */
1059 NULL, /* interface_finalize */
1060 NULL /* interface_data */
1062 type = g_type_register_static (G_TYPE_OBJECT,
1065 g_type_add_interface_static (type,
1068 g_type_add_interface_static (type,
1075 It is very important to notice that the order in which interface implementations are added to the main object
1076 is not random: <function><link linkend="g-type-add-interface-static">g_type_add_interface_static</link></function> must be invoked first on the interfaces which have
1077 no prerequisites and then on the others.
1081 Complete source code showing how to define the MamanIbar interface which requires MamanIbaz and how to
1082 implement the MamanIbar interface is located in <filename>sample/interface/maman-ibar.{h|c}</filename>
1083 and <filename>sample/interface/maman-bar.{h|c}</filename>.
1088 <sect1 id="howto-interface-properties">
1089 <title>Interface Properties</title>
1092 Starting from version 2.4 of GLib, GObject interfaces can also have properties.
1093 Declaration of the interface properties is similar to declaring the properties of
1094 ordinary GObject types as explained in <xref linkend="gobject-properties"/>,
1095 except that <function><link linkend="g-object-interface-install-property">g_object_interface_install_property</link></function> is used to
1096 declare the properties instead of <function><link linkend="g-object-class-install-property">g_object_class_install_property</link></function>.
1100 To include a property named 'name' of type <type>string</type> in the
1101 <type>maman_ibaz</type> interface example code above, we only need to add one
1104 That really is one line extended to six for the sake of clarity
1107 line in the <function>maman_ibaz_base_init</function>
1110 The <function><link linkend="g-object-interface-install-property">g_object_interface_install_property</link></function> can also be called from
1111 <function>class_init</function> but it must not be called after that point.
1117 maman_ibaz_base_init (gpointer g_iface)
1119 static gboolean initialized = FALSE;
1122 /* create interface signals here. */
1124 g_object_interface_install_property (g_iface,
1125 g_param_spec_string ("name",
1127 "Name of the MamanIbaz",
1129 G_PARAM_READWRITE));
1137 One point worth noting is that the declared property wasn't assigned an
1138 integer ID. The reason being that integer IDs of properties are utilized only
1139 inside the get and set methods and since interfaces do not implement properties,
1140 there is no need to assign integer IDs to interface properties.
1144 The story for the implementers of the interface is also quite trivial.
1145 An implementer shall declare and define it's properties in the usual way as
1146 explained in <xref linkend="gobject-properties"/>, except for one small
1147 change: it shall declare the properties of the interface it implements using
1148 <function><link linkend="g-object-class-override-property">g_object_class_override_property</link></function> instead of
1149 <function><link linkend="g-object-class-install-property">g_object_class_install_property</link></function>. The following code snippet
1150 shows the modifications needed in the <type>MamanBaz</type> declaration and
1151 implementation above:
1156 gint instance_member;
1157 gchar *name; /* placeholder for property */
1167 maman_baz_get_type (void)
1169 static GType type = 0;
1171 static const GTypeInfo info = {
1172 sizeof (MamanBazClass),
1173 NULL, /* base_init */
1174 NULL, /* base_finalize */
1175 baz_class_init, /* class_init */
1176 NULL, /* class_finalize */
1177 NULL, /* class_data */
1179 0, /* n_preallocs */
1180 baz_instance_init /* instance_init */
1182 static const GInterfaceInfo ibaz_info = {
1183 (GInterfaceInitFunc) baz_interface_init, /* interface_init */
1184 NULL, /* interface_finalize */
1185 NULL /* interface_data */
1187 type = g_type_register_static (G_TYPE_OBJECT,
1190 g_type_add_interface_static (type,
1198 maman_baz_class_init (MamanBazClass * klass)
1200 GObjectClass *gobject_class;
1202 gobject_class = (GObjectClass *) klass;
1204 parent_class = g_type_class_ref (G_TYPE_OBJECT);
1206 gobject_class->set_property = maman_baz_set_property;
1207 gobject_class->get_property = maman_baz_get_property;
1209 g_object_class_override_property (gobject_class, ARG_NAME, "name");
1213 maman_baz_set_property (GObject * object, guint prop_id,
1214 const GValue * value, GParamSpec * pspec)
1219 /* it's not null if we got it, but it might not be ours */
1220 g_return_if_fail (G_IS_MAMAN_BAZ (object));
1222 baz = MAMAN_BAZ (object);
1226 baz->name = g_value_get_string (value);
1229 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1235 maman_baz_get_property (GObject * object, guint prop_id,
1236 GValue * value, GParamSpec * pspec)
1240 /* it's not null if we got it, but it might not be ours */
1241 g_return_if_fail (G_IS_TEXT_PLUGIN (object));
1243 baz = MAMAN_BAZ (object);
1247 g_value_set_string (value, baz->name);
1250 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1260 <!-- End Howto Interfaces -->
1262 <chapter id="howto-signals">
1263 <title>How to create and use signals</title>
1267 The signal system which was built in GType is pretty complex and flexible: it is possible for its users
1268 to connect at runtime any number of callbacks (implemented in any language for which a binding exists)
1270 <para>A Python callback can be connected to any signal on any C-based GObject.
1274 to any signal and to stop the emission of any signal at any
1275 state of the signal emission process. This flexibility makes it possible to use GSignal for much more than
1276 just emit events which can be received by numerous clients.
1279 <sect1 id="howto-simple-signals">
1280 <title>Simple use of signals</title>
1283 The most basic use of signals is to implement simple event notification: for example, if we have a
1284 MamanFile object, and if this object has a write method, we might wish to be notified whenever someone
1285 uses this method. The code below shows how the user can connect a callback to the write signal. Full code
1286 for this simple example is located in <filename>sample/signal/maman-file.{h|c}</filename> and
1287 in <filename>sample/signal/test.c</filename>
1289 file = g_object_new (MAMAN_FILE_TYPE, NULL);
1291 g_signal_connect (G_OBJECT (file), "write",
1292 (GCallback)write_event,
1295 maman_file_write (file, buffer, 50);
1300 The <type>MamanFile</type> signal is registered in the class_init function:
1302 klass->write_signal_id =
1303 g_signal_newv ("write",
1304 G_TYPE_FROM_CLASS (g_class),
1305 G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS,
1306 NULL /* class closure */,
1307 NULL /* accumulator */,
1308 NULL /* accu_data */,
1309 g_cclosure_marshal_VOID__VOID,
1310 G_TYPE_NONE /* return_type */,
1312 NULL /* param_types */);
1314 and the signal is emitted in <function>maman_file_write</function>:
1316 void maman_file_write (MamanFile *self, guint8 *buffer, guint32 size)
1318 /* First write data. */
1319 /* Then, notify user of data written. */
1320 g_signal_emit (self, MAMAN_FILE_GET_CLASS (self)->write_signal_id,
1325 As shown above, you can safely set the details parameter to zero if you do not know what it can be used for.
1326 For a discussion of what you could used it for, see <xref linkend="signal-detail"/>
1330 The signature of the signal handler in the above example is defined as
1331 <function>g_cclosure_marshal_VOID__VOID</function>. Its name follows
1332 a simple convention which encodes the function parameter and return value
1333 types in the function name. Specifically, the value in front of the double
1334 underscore is the type of the return value, while the value(s) after the
1335 double underscore denote the parameter types.
1336 The header <filename>gobject/gmarshal.h</filename> defines a set of commonly
1337 needed closures that one can use.
1342 <title>How to provide more flexibility to users?</title>
1345 The previous implementation does the job but the signal facility of GObject can be used to provide
1346 even more flexibility to this file change notification mechanism. One of the key ideas is to make the process
1347 of writing data to the file part of the signal emission process to allow users to be notified either
1348 before or after the data is written to the file.
1352 To integrate the process of writing the data to the file into the signal emission mechanism, we can
1353 register a default class closure for this signal which will be invoked during the signal emission, just like
1354 any other user-connected signal handler.
1358 The first step to implement this idea is to change the signature of the signal: we need to pass
1359 around the buffer to write and its size. To do this, we use our own marshaller which will be generated
1360 through GLib's genmarshall tool. We thus create a file named <filename>marshall.list</filename> which contains
1361 the following single line:
1365 and use the Makefile provided in <filename>sample/signal/Makefile</filename> to generate the file named
1366 <filename>maman-file-complex-marshall.c</filename>. This C file is finally included in
1367 <filename>maman-file-complex.c</filename>.
1371 Once the marshaller is present, we register the signal and its marshaller in the class_init function
1372 of the object <type>MamanFileComplex</type> (full source for this object is included in
1373 <filename>sample/signal/maman-file-complex.{h|c}</filename>):
1375 GClosure *default_closure;
1376 GType param_types[2];
1378 default_closure = g_cclosure_new (G_CALLBACK (default_write_signal_handler),
1379 (gpointer)0xdeadbeaf /* user_data */,
1380 NULL /* destroy_data */);
1382 param_types[0] = G_TYPE_POINTER;
1383 param_types[1] = G_TYPE_UINT;
1384 klass->write_signal_id =
1385 g_signal_newv ("write",
1386 G_TYPE_FROM_CLASS (g_class),
1387 G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS,
1388 default_closure /* class closure */,
1389 NULL /* accumulator */,
1390 NULL /* accu_data */,
1391 maman_file_complex_VOID__POINTER_UINT,
1392 G_TYPE_NONE /* return_type */,
1394 param_types /* param_types */);
1396 The code shown above first creates the closure which contains the code to complete the file write. This
1397 closure is registered as the default class_closure of the newly created signal.
1401 Of course, you need to implement completely the code for the default closure since I just provided
1405 default_write_signal_handler (GObject *obj, guint8 *buffer, guint size, gpointer user_data)
1407 g_assert (user_data == (gpointer)0xdeadbeaf);
1408 /* Here, we trigger the real file write. */
1409 g_print ("default signal handler: 0x%x %u\n", buffer, size);
1415 Finally, the client code must invoke the <function>maman_file_complex_write</function> function which
1416 triggers the signal emission:
1418 void maman_file_complex_write (MamanFileComplex *self, guint8 *buffer, guint size)
1421 g_signal_emit (self,
1422 MAMAN_FILE_COMPLEX_GET_CLASS (self)->write_signal_id,
1430 The client code (as shown in <filename>sample/signal/test.c</filename> and below) can now connect signal handlers before
1431 and after the file write is completed: since the default signal handler which does the write itself runs during the
1432 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>
1433 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
1434 which emits signals, I would thus urge you to create all your signals with the G_SIGNAL_RUN_LAST such that your users
1435 have a maximum of flexibility as to when to get the event. Here, we combined it with G_SIGNAL_NO_RECURSE and
1436 G_SIGNAL_NO_HOOKS to ensure our users will not try to do really weird things with our GObject. I strongly advise you
1437 to do the same unless you really know why (in which case you really know the inner workings of GSignal by heart and
1438 you are not reading this).
1443 static void complex_write_event_before (GObject *file, guint8 *buffer, guint size, gpointer user_data)
1445 g_assert (user_data == NULL);
1446 g_print ("Complex Write event before: 0x%x, %u\n", buffer, size);
1449 static void complex_write_event_after (GObject *file, guint8 *buffer, guint size, gpointer user_data)
1451 g_assert (user_data == NULL);
1452 g_print ("Complex Write event after: 0x%x, %u\n", buffer, size);
1455 static void test_file_complex (void)
1460 file = g_object_new (MAMAN_FILE_COMPLEX_TYPE, NULL);
1462 g_signal_connect (G_OBJECT (file), "write",
1463 (GCallback)complex_write_event_before,
1466 g_signal_connect_after (G_OBJECT (file), "write",
1467 (GCallback)complex_write_event_after,
1470 maman_file_complex_write (MAMAN_FILE_COMPLEX (file), buffer, 50);
1472 g_object_unref (G_OBJECT (file));
1475 The code above generates the following output on my machine:
1477 Complex Write event before: 0xbfffe280, 50
1478 default signal handler: 0xbfffe280 50
1479 Complex Write event after: 0xbfffe280, 50
1485 <title>How most people do the same thing with less code</title>
1487 <para>For many historic reasons related to how the ancestor of GObject used to work in GTK+ 1.x versions,
1488 there is a much <emphasis>simpler</emphasis>
1490 <para>I personally think that this method is horribly mind-twisting: it adds a new indirection
1491 which unnecessarily complicates the overall code path. However, because this method is widely used
1492 by all of GTK+ and GObject code, readers need to understand it. The reason why this is done that way
1493 in most of GTK+ is related to the fact that the ancestor of GObject did not provide any other way to
1494 create a signal with a default handler than this one. Some people have tried to justify that it is done
1495 that way because it is better, faster (I am extremely doubtful about the faster bit. As a matter of fact,
1496 the better bit also mystifies me ;-). I have the feeling no one really knows and everyone does it
1497 because they copy/pasted code from code which did the same. It is probably better to leave this
1498 specific trivia to hacker legends domain...
1501 way to create a signal with a default handler than to create
1502 a closure by hand and to use the <function><link linkend="g-signal-newv">g_signal_newv</link></function>.
1505 <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
1506 handler which is stored in the class structure of the object. More specifically, the class structure
1507 contains a function pointer which is accessed during signal emission to invoke the default handler and
1508 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
1509 class structure to the function pointer.
1511 <para>I would like to point out here that the reason why the default handler of a signal is named everywhere
1512 a class_closure is probably related to the fact that it used to be really a function pointer stored in
1513 the class structure.
1518 <para>The following code shows the declaration of the <type>MamanFileSimple</type> class structure which contains
1519 the <function>write</function> function pointer.
1521 struct _MamanFileSimpleClass {
1522 GObjectClass parent;
1524 guint write_signal_id;
1526 /* signal default handlers */
1527 void (*write) (MamanFileSimple *self, guint8 *buffer, guint size);
1530 The <function>write</function> function pointer is initialized in the class_init function of the object
1531 to <function>default_write_signal_handler</function>:
1534 maman_file_simple_class_init (gpointer g_class,
1535 gpointer g_class_data)
1537 GObjectClass *gobject_class = G_OBJECT_CLASS (g_class);
1538 MamanFileSimpleClass *klass = MAMAN_FILE_SIMPLE_CLASS (g_class);
1540 klass->write = default_write_signal_handler;
1542 Finally, the signal is created with <function><link linkend="g-signal-new">g_signal_new</link></function> in the same class_init function:
1544 klass->write_signal_id =
1545 g_signal_new ("write",
1546 G_TYPE_FROM_CLASS (g_class),
1547 G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS,
1548 G_STRUCT_OFFSET (MamanFileSimpleClass, write),
1549 NULL /* accumulator */,
1550 NULL /* accu_data */,
1551 maman_file_complex_VOID__POINTER_UINT,
1552 G_TYPE_NONE /* return_type */,
1557 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>
1558 macro which indicates the offset of the member <emphasis>write</emphasis> from the start of the
1559 <type>MamanFileSimpleClass</type> class structure.
1561 <para>GSignal uses this offset to create a special wrapper closure
1562 which first retrieves the target function pointer before calling it.
1568 While the complete code for this type of default handler looks less cluttered as shown in
1569 <filename>sample/signal/maman-file-simple.{h|c}</filename>, it contains numerous subtleties.
1570 The main subtle point which everyone must be aware of is that the signature of the default
1571 handler created that way does not have a user_data argument:
1572 <function>default_write_signal_handler</function> is different in
1573 <filename>sample/signal/maman-file-complex.c</filename> and in
1574 <filename>sample/signal/maman-file-simple.c</filename>.
1577 <para>If you have doubts about which method to use, I would advise you to use the second one which
1578 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>:
1579 it is better to write code which looks like the vast majority of other GTK+/GObject code than to
1580 do it your own way. However, now, you know why.
1589 <title>How users can abuse signals (and why some think it is good)</title>
1591 <para>Now that you know how to create signals to which the users can connect easily and at any point in
1592 the signal emission process thanks to <function><link linkend="g-signal-connect">g_signal_connect</link></function>,
1593 <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
1594 users can and will screw you. This is also interesting to know how you too, can screw other people.
1595 This will make you feel good and eleet.
1601 <listitem><para>stop the emission of the signal at anytime</para></listitem>
1602 <listitem><para>override the default handler of the signal if it is stored as a function
1603 pointer in the class structure (which is the preferred way to create a default signal handler,
1604 as discussed in the previous section).</para></listitem>
1609 In both cases, the original programmer should be as careful as possible to write code which is
1610 resistant to the fact that the default handler of the signal might not able to run. This is obviously
1611 not the case in the example used in the previous sections since the write to the file depends on whether
1612 or not the default handler runs (however, this might be your goal: to allow the user to prevent the file
1613 write if he wishes to).
1617 If all you want to do is to stop the signal emission from one of the callbacks you connected yourself,
1618 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
1623 If the signal's default handler is just a class function pointer, it is also possible to override
1624 it yourself from the class_init function of a type which derives from the parent. That way, when the signal
1625 is emitted, the parent class will use the function provided by the child as a signal default handler.
1626 Of course, it is also possible (and recommended) to chain up from the child to the parent's default signal
1627 handler to ensure the integrity of the parent object.
1631 Overriding a class method and chaining up was demonstrated in <xref linkend="howto-gobject-methods"/>
1632 which is why I won't bother to show exactly how to do it here again.
1641 <title>Warning on signal creation and default closure</title>
1644 Most of the existing code I have seen up to now (in both GTK+, GNOME libraries and
1645 many GTK+ and GNOME applications) using signals uses a small
1646 variation of the default handler pattern I have shown in the previous section.
1650 Usually, the <function><link linkend="g-signal-new">g_signal_new</link></function> function is preferred over
1651 <function><link linkend="g-signal-newv">g_signal_newv</link></function>. When <function><link linkend="g-signal-new">g_signal_new</link></function>
1652 is used, the default closure is exported as a class function. For example,
1653 <filename>gobject.h</filename> contains the declaration of <type><link linkend="GObjectClass">GObjectClass</link></type>
1654 whose notify class function is the default handler for the <emphasis>notify</emphasis>
1657 struct _GObjectClass
1659 GTypeClass g_type_class;
1661 /* class methods and other stuff. */
1664 void (*notify) (GObject *object,
1671 <filename>gobject.c</filename>'s <function><link linkend="g-object-do-class-init">g_object_do_class_init</link></function> function
1672 registers the <emphasis>notify</emphasis> signal and initializes this class function
1676 g_object_do_class_init (GObjectClass *class)
1681 class->notify = NULL;
1683 gobject_signals[NOTIFY] =
1684 g_signal_new ("notify",
1685 G_TYPE_FROM_CLASS (class),
1686 G_SIGNAL_RUN_FIRST | G_SIGNAL_NO_RECURSE | G_SIGNAL_DETAILED | G_SIGNAL_NO_HOOKS,
1687 G_STRUCT_OFFSET (GObjectClass, notify),
1689 g_cclosure_marshal_VOID__PARAM,
1694 <function><link linkend="g-signal-new">g_signal_new</link></function> creates a <type><link linkend="GClosure">GClosure</link></type> which dereferences the
1695 type's class structure to access the class function pointer and invoke it if it not NULL. The
1696 class function is ignored it is set to NULL.
1700 To understand the reason for such a complex scheme to access the signal's default handler,
1701 you must remember the whole reason for the use of these signals. The goal here is to delegate
1702 a part of the process to the user without requiring the user to subclass the object to override
1703 one of the class functions. The alternative to subclassing, that is, the use of signals
1704 to delegate processing to the user, is, however, a bit less optimal in terms of speed: rather
1705 than just dereferencing a function pointer in a class structure, you must start the whole
1706 process of signal emission which is a bit heavyweight.
1710 This is why some people decided to use class functions for some signal's default handlers:
1711 rather than having users connect a handler to the signal and stop the signal emission
1712 from within that handler, you just need to override the default class function which is
1713 supposedly more efficient.