docs: rename *-docs.sgml to *-docs.xml
[platform/upstream/glib.git] / docs / reference / gobject / tut_gtype.xml
1 <?xml version='1.0' encoding="ISO-8859-1"?>
2 <!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN" 
3                "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd" [
4 ]>
5   <chapter id="chapter-gtype">
6     <title>The GLib Dynamic Type System</title>
7
8       <para>
9         A type, as manipulated by the GLib type system, is much more generic than what
10         is usually understood as an Object type. It is best explained by looking at the 
11         structure and the functions used to register new types in the type system.
12         <programlisting>
13 typedef struct _GTypeInfo               GTypeInfo;
14 struct _GTypeInfo
15 {
16   /* interface types, classed types, instantiated types */
17   guint16                class_size;
18   
19   GBaseInitFunc          base_init;
20   GBaseFinalizeFunc      base_finalize;
21   
22   /* classed types, instantiated types */
23   GClassInitFunc         class_init;
24   GClassFinalizeFunc     class_finalize;
25   gconstpointer          class_data;
26   
27   /* instantiated types */
28   guint16                instance_size;
29   guint16                n_preallocs;
30   GInstanceInitFunc      instance_init;
31   
32   /* value handling */
33   const GTypeValueTable *value_table;
34 };
35 GType g_type_register_static (GType             parent_type,
36                               const gchar      *type_name,
37                               const GTypeInfo  *info,
38                               GTypeFlags        flags);
39 GType g_type_register_fundamental (GType                       type_id,
40                                    const gchar                *type_name,
41                                    const GTypeInfo            *info,
42                                    const GTypeFundamentalInfo *finfo,
43                                    GTypeFlags                  flags);
44         </programlisting>
45       </para>
46
47       <para>
48         <function><link linkend="g-type-register-static">g_type_register_static</link></function> and 
49         <function><link linkend="g-type-register-fundamental">g_type_register_fundamental</link></function>
50         are the C functions, defined in
51         <filename>gtype.h</filename> and implemented in <filename>gtype.c</filename>
52         which you should use to register a new <link linkend="GType"><type>GType</type></link> in the program's type system.
53         It is not likely you will ever need to use 
54         <function><link linkend="g-type-register-fundamental">g_type_register_fundamental</link></function> (you have to be Tim Janik 
55         to do that) but in case you want to, the last chapter explains how to create
56         new fundamental types.
57         <footnote>
58           <para>
59             Please note that there exists another registration function: the 
60             <function><link linkend="g-type-register-dynamic">g_type_register_dynamic</link></function>. We will not discuss this
61             function here since its use is very similar to the <function>_static</function> 
62             version.
63           </para>
64         </footnote>
65       </para>
66
67       <para>
68         Fundamental types are top-level types which do not derive from any other type 
69         while other non-fundamental types derive from other types.
70         Upon initialization by <function><link linkend="g-type-init">g_type_init</link></function>, the type system not 
71         only initializes its internal data structures but it also registers a number of core
72         types: some of these are fundamental types. Others are types derived from these 
73         fundamental types.
74       </para>
75
76       <para>
77         Fundamental and non-fundamental types are defined by:
78         <itemizedlist>
79           <listitem><para>
80             class size: the class_size field in <link linkend="GTypeInfo"><type>GTypeInfo</type></link>.
81           </para></listitem>
82           <listitem><para>
83             class initialization functions (C++ constructor): the base_init and 
84             class_init fields in <link linkend="GTypeInfo"><type>GTypeInfo</type></link>.
85           </para></listitem>
86           <listitem><para>
87             class destruction functions (C++ destructor): the base_finalize and 
88             class_finalize fields in <link linkend="GTypeInfo"><type>GTypeInfo</type></link>.
89           </para></listitem>
90           <listitem><para>
91             instance size (C++ parameter to new): the instance_size field in 
92             <link linkend="GTypeInfo"><type>GTypeInfo</type></link>.
93           </para></listitem>
94           <listitem><para>
95             instantiation policy (C++ type of new operator): the n_preallocs
96             field in <link linkend="GTypeInfo"><type>GTypeInfo</type></link>.
97           </para></listitem>
98           <listitem><para>
99             copy functions (C++ copy operators): the value_table field in 
100             <link linkend="GTypeInfo"><type>GTypeInfo</type></link>.
101           </para></listitem>
102           <listitem><para>
103             type characteristic flags: <link linkend="GTypeFlags"><type>GTypeFlags</type></link>.
104           </para></listitem>
105         </itemizedlist>
106         Fundamental types are also defined by a set of <link linkend="GTypeFundamentalFlags"><type>GTypeFundamentalFlags</type></link> 
107         which are stored in a <link linkend="GTypeFundamentalInfo"><type>GTypeFundamentalInfo</type></link>.
108         Non-fundamental types are furthermore defined by the type of their parent which is
109         passed as the parent_type parameter to <function><link linkend="g-type-register-static">g_type_register_static</link></function>
110         and <function><link linkend="g-type-register-dynamic">g_type_register_dynamic</link></function>.
111       </para>
112       
113       <sect1 id="gtype-copy">
114         <title>Copy functions</title>
115
116         <para>
117           The major common point between <emphasis>all</emphasis> GLib types (fundamental and 
118           non-fundamental, classed and non-classed, instantiable and non-instantiable) is that
119           they can all be manipulated through a single API to copy/assign them.
120         </para>
121
122         <para>
123           The <link linkend="GValue"><type>GValue</type></link> structure is used as an abstract container for all of these 
124           types. Its simplistic API (defined in <filename>gobject/gvalue.h</filename>) can be 
125           used to invoke the value_table functions registered
126           during type registration: for example <function><link linkend="g-value-copy">g_value_copy</link></function> copies the 
127           content of a <link linkend="GValue"><type>GValue</type></link> to another <link linkend="GValue"><type>GValue</type></link>. This is similar
128           to a C++ assignment which invokes the C++ copy operator to modify the default
129           bit-by-bit copy semantics of C++/C structures/classes.
130         </para>
131
132         <para>
133           The following code shows how you can copy around a 64 bit integer, as well as a <link linkend="GObject"><type>GObject</type></link>
134           instance pointer (sample code for this is located in the source tarball for this document in 
135           <filename>sample/gtype/test.c</filename>):
136 <programlisting>
137 static void test_int (void)
138 {
139   GValue a_value = G_VALUE_INIT;
140   GValue b_value = G_VALUE_INIT;
141   guint64 a, b;
142
143   a = 0xdeadbeaf;
144
145   g_value_init (&amp;a_value, G_TYPE_UINT64);
146   g_value_set_uint64 (&amp;a_value, a);
147
148   g_value_init (&amp;b_value, G_TYPE_UINT64);
149   g_value_copy (&amp;a_value, &amp;b_value);
150
151   b = g_value_get_uint64 (&amp;b_value);
152
153   if (a == b) {
154     g_print ("Yay !! 10 lines of code to copy around a uint64.\n");
155   } else {
156     g_print ("Are you sure this is not a Z80 ?\n");
157   }
158 }
159
160 static void test_object (void)
161 {
162   GObject *obj;
163   GValue obj_vala = G_VALUE_INIT;
164   GValue obj_valb = G_VALUE_INIT;
165   obj = g_object_new (MAMAN_TYPE_BAR, NULL);
166
167   g_value_init (&amp;obj_vala, MAMAN_TYPE_BAR);
168   g_value_set_object (&amp;obj_vala, obj);
169
170   g_value_init (&amp;obj_valb, G_TYPE_OBJECT);
171
172   /* g_value_copy's semantics for G_TYPE_OBJECT types is to copy the reference.
173      This function thus calls g_object_ref.
174      It is interesting to note that the assignment works here because
175      MAMAN_TYPE_BAR is a G_TYPE_OBJECT.
176    */
177   g_value_copy (&amp;obj_vala, &amp;obj_valb);
178
179   g_object_unref (G_OBJECT (obj));
180   g_object_unref (G_OBJECT (obj));
181 }
182 </programlisting>
183           The important point about the above code is that the exact semantics of the copy calls
184           is undefined since they depend on the implementation of the copy function. Certain 
185           copy functions might decide to allocate a new chunk of memory and then to copy the 
186           data from the source to the destination. Others might want to simply increment
187           the reference count of the instance and copy the reference to the new GValue.
188         </para>
189         
190         <para>
191           The value_table used to specify these assignment functions is defined in
192           <filename>gtype.h</filename> and is thoroughly described in the
193           API documentation provided with GObject (for once ;-) which is why we will
194           not detail its exact semantics. 
195           <programlisting>
196 typedef struct _GTypeValueTable         GTypeValueTable;
197 struct _GTypeValueTable
198 {
199   void     (*value_init)         (GValue       *value);
200   void     (*value_free)         (GValue       *value);
201   void     (*value_copy)         (const GValue *src_value,
202                                   GValue       *dest_value);
203   /* varargs functionality (optional) */
204   gpointer (*value_peek_pointer) (const GValue *value);
205   gchar            *collect_format;
206   gchar*   (*collect_value)      (GValue       *value,
207                                   guint         n_collect_values,
208                                   GTypeCValue  *collect_values,
209                                   guint                collect_flags);
210   gchar            *lcopy_format;
211   gchar*   (*lcopy_value)        (const GValue *value,
212                                   guint         n_collect_values,
213                                   GTypeCValue  *collect_values,
214                                   guint                collect_flags);
215 };
216           </programlisting>
217           Interestingly, it is also very unlikely
218           you will ever need to specify a value_table during type registration
219           because these value_tables are inherited from the parent types for
220           non-fundamental types which means that unless you want to write a 
221           fundamental type (not a great idea!), you will not need to provide
222           a new value_table since you will inherit the value_table structure
223           from your parent type.
224         </para>
225       </sect1>
226
227       <sect1 id="gtype-conventions">
228         <title>Conventions</title>
229
230
231       <para>
232         There are a number of conventions users are expected to follow when creating new types
233         which are to be exported in a header file:
234         <itemizedlist>
235           <listitem><para>
236             Use the <function>object_method</function> pattern for function names: to invoke
237             the method named foo on an instance of object type bar, call 
238             <function>bar_foo</function>.
239           </para></listitem>
240           <listitem><para>Use prefixing to avoid namespace conflicts with other projects.
241             If your library (or application) is named <emphasis>Maman</emphasis>,
242             <footnote>
243               <para>
244                 <emphasis>Maman</emphasis> is the French word for <emphasis>mum</emphasis>
245                 or <emphasis>mother</emphasis> - nothing more and nothing less.
246               </para>
247             </footnote>
248             
249             prefix all your function names with <emphasis>maman_</emphasis>.
250             For example: <function>maman_object_method</function>.
251           </para></listitem>
252           <listitem><para>Create a macro named <function>PREFIX_TYPE_OBJECT</function> which always 
253             returns the GType for the associated object type. For an object of type 
254             <emphasis>Bar</emphasis> in a library prefixed by <emphasis>maman</emphasis>, 
255             use: <function>MAMAN_TYPE_BAR</function>.
256             It is common although not a convention to implement this macro using either a global 
257             static variable or a function named <function>prefix_object_get_type</function>.
258             We will follow the function pattern wherever possible in this document.
259           </para></listitem>
260           <listitem><para>Create a macro named <function>PREFIX_OBJECT (obj)</function> which 
261             returns a pointer of type <type>PrefixObject</type>. This macro is used to enforce
262             static type safety by doing explicit casts wherever needed. It also enforces
263             dynamic type safety by doing runtime checks. It is possible to disable the dynamic
264             type checks in production builds (see <link linkend="glib-building">building glib</link>).
265             For example, we would create 
266             <function>MAMAN_BAR (obj)</function> to keep the previous example.
267           </para></listitem>
268           <listitem><para>If the type is classed, create a macro named 
269             <function>PREFIX_OBJECT_CLASS (klass)</function>. This macro
270             is strictly equivalent to the previous casting macro: it does static casting with
271             dynamic type checking of class structures. It is expected to return a pointer
272             to a class structure of type <type>PrefixObjectClass</type>. Again, an example is:
273             <function>MAMAN_BAR_CLASS</function>.
274           </para></listitem>
275           <listitem><para>Create a macro named <function>PREFIX_IS_BAR (obj)</function>: this macro is expected
276             to return a <type>gboolean</type> which indicates whether or not the input
277             object instance pointer of type BAR.
278           </para></listitem>
279           <listitem><para>If the type is classed, create a macro named
280             <function>PREFIX_IS_OBJECT_CLASS (klass)</function> which, as above, returns a boolean
281             if the input class pointer is a pointer to a class of type OBJECT.
282           </para></listitem>
283           <listitem><para>If the type is classed, create a macro named 
284             <function>PREFIX_OBJECT_GET_CLASS (obj)</function>
285             which returns the class pointer associated to an instance of a given type. This macro
286             is used for static and dynamic type safety purposes (just like the previous casting
287             macros).
288           </para></listitem>
289         </itemizedlist>
290         The implementation of these macros is pretty straightforward: a number of simple-to-use 
291         macros are provided in <filename>gtype.h</filename>. For the example we used above, we would 
292         write the following trivial code to declare the macros:
293 <programlisting>
294 #define MAMAN_TYPE_BAR                  (maman_bar_get_type ())
295 #define MAMAN_BAR(obj)                  (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_TYPE_BAR, MamanBar))
296 #define MAMAN_BAR_CLASS(klass)          (G_TYPE_CHECK_CLASS_CAST ((klass), MAMAN_TYPE_BAR, MamanBarClass))
297 #define MAMAN_IS_BAR(obj)          (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_TYPE_BAR))
298 #define MAMAN_IS_BAR_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), MAMAN_TYPE_BAR))
299 #define MAMAN_BAR_GET_CLASS(obj)  (G_TYPE_INSTANCE_GET_CLASS ((obj), MAMAN_TYPE_BAR, MamanBarClass))
300 </programlisting>
301         <note><simpara>Stick to the naming <varname>klass</varname> as <varname>class</varname> is a registered c++ keyword.</simpara></note>
302       </para>
303
304       <para>
305         The following code shows how to implement the <function>maman_bar_get_type</function>
306         function:
307 <programlisting>
308 GType maman_bar_get_type (void)
309 {
310   static GType type = 0;
311   if (type == 0) {
312     const GTypeInfo info = {
313       /* You fill this structure. */
314     };
315     type = g_type_register_static (G_TYPE_OBJECT,
316                                    "MamanBarType",
317                                    &amp;info, 0);
318   }
319   return type;
320 }
321 </programlisting>
322       </para>
323
324       <para>
325         When having no special requirements you also can use the <function>G_DEFINE_TYPE</function>
326         macro:
327 <programlisting>
328 G_DEFINE_TYPE (MamanBar, maman_bar, G_TYPE_OBJECT)
329 </programlisting>
330       </para>
331
332       </sect1>
333
334       <sect1 id="gtype-non-instantiable">
335         <title>Non-instantiable non-classed fundamental types</title>
336
337         <para>
338           A lot of types are not instantiable by the type system and do not have
339           a class. Most of these types are fundamental trivial types such as <emphasis>gchar</emphasis>, 
340           registered in <function>_g_value_types_init</function> (in <filename>gvaluetypes.c</filename>).
341         </para>
342
343         <para>
344           To register such a type in the type system, you just need to fill the 
345           <link linkend="GTypeInfo"><type>GTypeInfo</type></link> structure with zeros since these types are also most of the time
346           fundamental:
347           <programlisting>
348   GTypeInfo info = {
349     0,                                /* class_size */
350     NULL,                        /* base_init */
351     NULL,                        /* base_destroy */
352     NULL,                        /* class_init */
353     NULL,                        /* class_destroy */
354     NULL,                        /* class_data */
355     0,                                /* instance_size */
356     0,                                /* n_preallocs */
357     NULL,                        /* instance_init */
358     NULL,                        /* value_table */
359   };
360   static const GTypeValueTable value_table = {
361     value_init_long0,                /* value_init */
362     NULL,                        /* value_free */
363     value_copy_long0,                /* value_copy */
364     NULL,                        /* value_peek_pointer */
365     "i",                        /* collect_format */
366     value_collect_int,        /* collect_value */
367     "p",                        /* lcopy_format */
368     value_lcopy_char,                /* lcopy_value */
369   };
370   info.value_table = &amp;value_table;
371   type = g_type_register_fundamental (G_TYPE_CHAR, "gchar", &amp;info, &amp;finfo, 0);
372           </programlisting>
373         </para>
374
375
376         <para>
377           Having non-instantiable types might seem a bit useless: what good is a type
378           if you cannot instantiate an instance of that type ? Most of these types
379           are used in conjunction with <link linkend="GValue"><type>GValue</type></link>s: a GValue is initialized
380           with an integer or a string and it is passed around by using the registered 
381           type's value_table. <link linkend="GValue"><type>GValue</type></link>s (and by extension these trivial fundamental
382           types) are most useful when used in conjunction with object properties and signals.
383         </para>
384
385       </sect1>
386
387       <sect1 id="gtype-instantiable-classed">
388         <title>Instantiable classed types: objects</title>
389
390         <para>
391           Types which are registered with a class and are declared instantiable are
392           what most closely resembles an <emphasis>object</emphasis>. 
393           Although <link linkend="GObject"><type>GObject</type></link>s (detailed in <xref linkend="chapter-gobject"/>) 
394           are the most well known type of instantiable
395           classed types, other kinds of similar objects used as the base of an inheritance 
396           hierarchy have been externally developed and they are all built on the fundamental
397           features described below.
398         </para>
399
400         <para>
401           For example, the code below shows how you could register 
402           such a fundamental object type in the type system:
403 <programlisting>
404 typedef struct {
405   GObject parent;
406   /* instance members */
407   int field_a;
408 } MamanBar;
409
410 typedef struct {
411   GObjectClass parent;
412   /* class members */
413   void (*do_action_public_virtual) (MamanBar *self, guint8 i);
414
415   void (*do_action_public_pure_virtual) (MamanBar *self, guint8 i);
416 } MamanBarClass;
417
418 #define MAMAN_TYPE_BAR (maman_bar_get_type ())
419
420 GType 
421 maman_bar_get_type (void)
422 {
423   static GType type = 0;
424   if (type == 0) {
425     const GTypeInfo info = {
426       sizeof (MamanBarClass),
427       NULL,           /* base_init */
428       NULL,           /* base_finalize */
429       (GClassInitFunc) foo_class_init,
430       NULL,           /* class_finalize */
431       NULL,           /* class_data */
432       sizeof (MamanBar),
433       0,              /* n_preallocs */
434       (GInstanceInitFunc) NULL /* instance_init */
435     };
436     type = g_type_register_static (G_TYPE_OBJECT,
437                                    "BarType",
438                                    &amp;info, 0);
439   }
440   return type;
441 }
442 </programlisting>
443           Upon the first call to <function>maman_bar_get_type</function>, the type named
444           <emphasis>BarType</emphasis> will be registered in the type system as inheriting
445           from the type <emphasis>G_TYPE_OBJECT</emphasis>.
446         </para>
447
448         <para>
449           Every object must define two structures: its class structure and its 
450           instance structure. All class structures must contain as first member
451           a <link linkend="GTypeClass"><type>GTypeClass</type></link> structure. All instance structures must contain as first
452           member a <link linkend="GTypeInstance"><type>GTypeInstance</type></link> structure. The declaration of these C types,
453           coming from <filename>gtype.h</filename> is shown below:
454 <programlisting>
455 struct _GTypeClass
456 {
457   GType g_type;
458 };
459 struct _GTypeInstance
460 {
461   GTypeClass *g_class;
462 };
463 </programlisting>
464           These constraints allow the type system to make sure that every object instance
465           (identified by a pointer to the object's instance structure) contains in its
466           first bytes a pointer to the object's class structure.
467         </para>
468         <para>
469           This relationship is best explained by an example: let's take object B which
470           inherits from object A:
471 <programlisting>
472 /* A definitions */
473 typedef struct {
474   GTypeInstance parent;
475   int field_a;
476   int field_b;
477 } A;
478 typedef struct {
479   GTypeClass parent_class;
480   void (*method_a) (void);
481   void (*method_b) (void);
482 } AClass;
483
484 /* B definitions. */
485 typedef struct {
486   A parent;
487   int field_c;
488   int field_d;
489 } B;
490 typedef struct {
491   AClass parent_class;
492   void (*method_c) (void);
493   void (*method_d) (void);
494 } BClass;
495 </programlisting>          
496           The C standard mandates that the first field of a C structure is stored starting
497           in the first byte of the buffer used to hold the structure's fields in memory.
498           This means that the first field of an instance of an object B is A's first field
499           which in turn is GTypeInstance's first field which in turn is g_class, a pointer
500           to B's class structure.
501         </para>
502
503         <para>
504           Thanks to these simple conditions, it is possible to detect the type of every
505           object instance by doing: 
506 <programlisting>
507 B *b;
508 b->parent.parent.g_class->g_type
509 </programlisting>
510           or, more quickly:
511 <programlisting>
512 B *b;
513 ((GTypeInstance*)b)->g_class->g_type
514 </programlisting>
515         </para>
516
517         <sect2 id="gtype-instantiable-classed-init-done">
518           <title>Initialization and Destruction</title>
519
520           <para>
521             instantiation of these types can be done with 
522             <function><link linkend="g-type-create-instance">g_type_create_instance</link></function>:
523 <programlisting>
524 GTypeInstance* g_type_create_instance (GType          type);
525 void           g_type_free_instance   (GTypeInstance *instance);
526 </programlisting>
527             <function><link linkend="g-type-create-instance">g_type_create_instance</link></function> will look up the type information
528             structure associated to the type requested. Then, the instance size and instantiation
529             policy (if the n_preallocs field is set to a non-zero value, the type system allocates
530             the object's instance structures in chunks rather than mallocing for every instance)
531             declared by the user are used to get a buffer to hold the object's instance
532             structure.
533           </para>
534
535           <para>
536             If this is the first instance of the object ever created, the type system must create a class structure.
537             It allocates a buffer to hold the object's class structure and initializes it. The first part of the
538             class structure (ie: the embedded parent class structure) is initialized by copying the contents from
539             the class structure of the parent class. The rest of class structure is initialized to zero.  If there
540             is no parent, the entire class structure is initialized to zero. The type system then invokes the
541             base_class_initialization functions (<link linkend="GBaseInitFunc"><type>GBaseInitFunc</type></link>) from topmost 
542             fundamental object to bottom-most most derived object. The object's class_init 
543             (<link linkend="GClassInitFunc"><type>GClassInitFunc</type></link>) function is invoked afterwards to complete
544             initialization of the class structure.
545             Finally, the object's interfaces are initialized (we will discuss interface initialization
546             in more detail later).
547           </para>
548
549           <para>
550             Once the type system has a pointer to an initialized class structure, it sets the object's
551             instance class pointer to the object's class structure and invokes the object's
552             instance_init (<link linkend="GInstanceInitFunc"><type>GInstanceInitFunc</type></link>)functions, from top-most fundamental 
553             type to bottom-most most derived type.
554           </para>
555
556           <para>
557             Object instance destruction through <function><link linkend="g-type-free-instance">g_type_free_instance</link></function> is very simple:
558             the instance structure is returned to the instance pool if there is one and if this was the
559             last living instance of the object, the class is destroyed.
560           </para>
561
562
563           <para>
564             Class destruction (the concept of destruction is sometimes partly 
565             referred to as finalization in GType) is the symmetric process of 
566             the initialization: interfaces are destroyed first. 
567             Then, the most derived 
568             class_finalize (<link linkend="GClassFinalizeFunc"><type>GClassFinalizeFunc</type></link>) function is invoked. The 
569             base_class_finalize (<link linkend="GBaseFinalizeFunc"><type>GBaseFinalizeFunc</type></link>) functions are 
570             Finally invoked from bottom-most most-derived type to top-most fundamental type and 
571             the class structure is freed.
572           </para>
573
574           <para>
575             As many readers have now understood it, the base initialization/finalization process is
576             very similar to the C++ constructor/destructor paradigm. The practical details are different
577             though and it is important not to get confused by superficial similarities. 
578             GTypes have no instance destruction mechanism. It is
579             the user's responsibility to implement correct destruction semantics on top
580             of the existing GType code. (this is what GObject does. See 
581             <xref linkend="chapter-gobject"/>)
582            Furthermore, C++ code equivalent to the base_init 
583            and class_init callbacks of GType is usually not needed because C++ cannot really create object 
584            types at runtime.
585           </para>
586
587           <para>
588             The instantiation/finalization process can be summarized as follows:
589             <table id="gtype-init-fini-table">
590               <title>GType Instantiation/Finalization</title>
591               <tgroup cols="3">
592                 <colspec colwidth="*" colnum="1" align="left"/>
593                 <colspec colwidth="*" colnum="2" align="left"/>
594                 <colspec colwidth="8*" colnum="3" align="left"/>
595     
596                 <thead>
597                   <row>
598                     <entry>Invocation time</entry>
599                     <entry>Function Invoked</entry>
600                     <entry>Function's parameters</entry>
601                   </row>
602                 </thead>
603                 <tbody>
604                   <row>
605                     <entry morerows="2">First call to <function><link linkend="g-type-create-instance">g_type_create_instance</link></function> for target type</entry>
606                     <entry>type's base_init function</entry>
607                     <entry>On the inheritance tree of classes from fundamental type to target type. 
608                       base_init is invoked once for each class structure.</entry>
609                   </row>
610                   <row>
611                     <!--entry>First call to <function><link linkend="g-type-create-instance">g_type_create_instance</link></function> for target type</entry-->
612                     <entry>target type's class_init function</entry>
613                     <entry>On target type's class structure</entry>
614                   </row>
615                   <row>
616                     <!--entry>First call to <function><link linkend="g-type-create-instance">g_type_create_instance</link></function> for target type</entry-->
617                     <entry>interface initialization, see 
618                       <xref linkend="gtype-non-instantiable-classed-init"/></entry>
619                     <entry></entry>
620                   </row>
621                   <row>
622                     <entry>Each call to <function><link linkend="g-type-create-instance">g_type_create_instance</link></function> for target type</entry>
623                     <entry>target type's instance_init function</entry>
624                     <entry>On object's instance</entry>
625                   </row>
626                   <row>
627                     <entry morerows="2">Last call to <function><link linkend="g-type-free-instance">g_type_free_instance</link></function> for target type</entry>
628                     <entry>interface destruction, see
629                       <xref linkend="gtype-non-instantiable-classed-dest"/></entry>
630                     <entry></entry>
631                   </row>
632                   <row>
633                     <!--entry>Last call to <function><link linkend="g-type-free-instance">g_type_free_instance</link></function> for target type</entry-->
634                     <entry>target type's class_finalize function</entry>
635                     <entry>On target type's class structure</entry>
636                   </row>
637                   <row>
638                     <!--entry>Last call to <function><link linkend="g-type-free-instance">g_type_free_instance</link></function> for target type</entry-->
639                     <entry>type's base_finalize function</entry>
640                     <entry>On the inheritance tree of classes from fundamental type to target type. 
641                       base_finalize is invoked once for each class structure.</entry>
642                   </row>
643                 </tbody>
644               </tgroup>
645             </table>
646           </para>
647           
648         </sect2>
649
650       </sect1>
651
652       <sect1 id="gtype-non-instantiable-classed">
653         <title>Non-instantiable classed types: interfaces</title>
654
655         <para>
656           GType's interfaces are very similar to Java's interfaces. They allow
657           to describe a common API that several classes will adhere to.
658           Imagine the play, pause and stop buttons on hi-fi equipment - those can
659           be seen as a playback interface. Once you know what they do, you can
660           control your CD player, MP3 player or anything that uses these symbols.
661           To declare an interface you have to register a non-instantiable
662           classed type which derives from 
663           <link linkend="GTypeInterface"><type>GTypeInterface</type></link>. The following piece of code declares such an interface.
664 <programlisting>
665 #define MAMAN_TYPE_IBAZ                (maman_ibaz_get_type ())
666 #define MAMAN_IBAZ(obj)                (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_TYPE_IBAZ, MamanIbaz))
667 #define MAMAN_IS_IBAZ(obj)             (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_TYPE_IBAZ))
668 #define MAMAN_IBAZ_GET_INTERFACE(inst) (G_TYPE_INSTANCE_GET_INTERFACE ((inst), MAMAN_TYPE_IBAZ, MamanIbazInterface))
669
670 typedef struct _MamanIbaz MamanIbaz; /* dummy object */
671 typedef struct _MamanIbazInterface MamanIbazInterface;
672
673 struct _MamanIbazInterface {
674   GTypeInterface parent;
675
676   void (*do_action) (MamanIbaz *self);
677 };
678
679 GType maman_ibaz_get_type (void);
680
681 void maman_ibaz_do_action (MamanIbaz *self);
682 </programlisting>
683           The interface function, <function>maman_ibaz_do_action</function> is implemented
684           in a pretty simple way:
685 <programlisting>
686 void maman_ibaz_do_action (MamanIbaz *self)
687 {
688   MAMAN_IBAZ_GET_INTERFACE (self)->do_action (self);
689 }
690 </programlisting>
691          <function>maman_ibaz_get_type</function> registers a type named <emphasis>MamanIBaz</emphasis>
692          which inherits from G_TYPE_INTERFACE. All interfaces must be children of G_TYPE_INTERFACE in the 
693          inheritance tree.
694         </para>
695
696         <para>
697           An interface is defined by only one structure which must contain as first member
698           a <link linkend="GTypeInterface"><type>GTypeInterface</type></link> structure. The interface structure is expected to
699           contain the function pointers of the interface methods. It is good style to 
700           define helper functions for each of the interface methods which simply call
701           the interface' method directly: <function>maman_ibaz_do_action</function>
702           is one of these.
703         </para>
704
705         <para>
706           Once an interface type is registered, you must register implementations for these
707           interfaces. The function named <function>maman_baz_get_type</function> registers
708           a new GType named MamanBaz which inherits from <link linkend="GObject"><type>GObject</type></link> and which
709           implements the interface <type>MamanIBaz</type>.
710 <programlisting>
711 static void maman_baz_do_action (MamanIbaz *self)
712 {
713   g_print ("Baz implementation of IBaz interface Action.\n");
714 }
715
716
717 static void
718 baz_interface_init (gpointer         g_iface,
719                     gpointer         iface_data)
720 {
721   MamanIbazInterface *iface = (MamanIbazInterface *)g_iface;
722   iface->do_action = maman_baz_do_action;
723 }
724
725 GType 
726 maman_baz_get_type (void)
727 {
728   static GType type = 0;
729   if (type == 0) {
730     const GTypeInfo info = {
731       sizeof (MamanBazInterface),
732       NULL,   /* base_init */
733       NULL,   /* base_finalize */
734       NULL,   /* class_init */
735       NULL,   /* class_finalize */
736       NULL,   /* class_data */
737       sizeof (MamanBaz),
738       0,      /* n_preallocs */
739       NULL    /* instance_init */
740     };
741     const GInterfaceInfo ibaz_info = {
742       (GInterfaceInitFunc) baz_interface_init,    /* interface_init */
743       NULL,               /* interface_finalize */
744       NULL          /* interface_data */
745     };
746     type = g_type_register_static (G_TYPE_OBJECT,
747                                    "MamanBazType",
748                                    &amp;info, 0);
749     g_type_add_interface_static (type,
750                                  MAMAN_TYPE_IBAZ,
751                                  &amp;ibaz_info);
752   }
753   return type;
754 }
755 </programlisting>
756         </para>
757
758         <para>
759           <function><link linkend="g-type-add-interface-static">g_type_add_interface_static</link></function> records in the type system that
760           a given type implements also <type>FooInterface</type> 
761           (<function>foo_interface_get_type</function> returns the type of 
762           <type>FooInterface</type>).
763                 The <link linkend="GInterfaceInfo"><type>GInterfaceInfo</type></link> structure holds
764           information about the implementation of the interface:
765 <programlisting>
766 struct _GInterfaceInfo
767 {
768   GInterfaceInitFunc     interface_init;
769   GInterfaceFinalizeFunc interface_finalize;
770   gpointer               interface_data;
771 };
772 </programlisting>
773         </para>
774         <para>
775         When having no special requirements you also can use the <function>G_DEFINE_INTERFACE</function> macro:
776 <programlisting>
777 G_DEFINE_INTERFACE (MamanBaz, maman_baz, G_TYPE_OBJECT)
778 </programlisting>
779         </para>
780
781
782         <sect2 id="gtype-non-instantiable-classed-init">
783           <title>Interface Initialization</title>
784
785           <para>
786             When an instantiable classed type which registered an interface 
787             implementation is created for the first time, its class structure 
788             is initialized following the process
789             described in <xref linkend="gtype-instantiable-classed"/>. 
790             After that, the interface implementations associated with
791             the type are initialized.
792           </para>
793
794           <para>
795             First a memory buffer is allocated to hold the interface structure. The parent's
796             interface structure is then copied over to the new interface structure (the parent
797             interface is already initialized at that point). If there is no parent interface,
798             the interface structure is initialized with zeros. The g_type and the g_instance_type
799             fields are then initialized: g_type is set to the type of the most-derived interface
800             and g_instance_type is set to the type of the most derived type which implements 
801             this interface.
802           </para>
803
804           <para>
805             Finally, the interface' most-derived <function>base_init</function> function and then 
806             the implementation's <function>interface_init</function>
807             function are invoked. It is important to understand that if there are multiple 
808             implementations of an interface the <function>base_init</function> and 
809             <function>interface_init</function> functions will be
810             invoked once for each implementation initialized.
811           </para>
812
813           <para>
814             It is thus common for base_init functions to hold a local static boolean variable
815             which makes sure that the interface type is initialized only once even if there are 
816             multiple implementations of the interface:
817 <programlisting>
818 static void
819 maman_ibaz_base_init (gpointer g_iface)
820 {
821   static gboolean initialized = FALSE;
822
823   if (!initialized) {
824     /* create interface signals here. */
825     initialized = TRUE;
826   }
827 }
828 </programlisting>
829           </para>
830
831         <para>
832           If you have found the stuff about interface hairy, you are right: it is hairy but
833           there is not much I can do about it. What I can do is summarize what you need to know
834           about interfaces:          
835         </para>
836
837           <para>
838             The above process can be summarized as follows:
839           <table id="ginterface-init-table">
840             <title>Interface Initialization</title>
841             <tgroup cols="3">
842               <colspec colwidth="*" colnum="1" align="left"/>
843               <colspec colwidth="*" colnum="2" align="left"/>
844               <colspec colwidth="8*" colnum="3" align="left"/>
845               
846               <thead>
847                 <row>
848                   <entry>Invocation time</entry>
849                   <entry>Function Invoked</entry>
850                   <entry>Function's parameters</entry>
851                   <entry>Remark</entry>
852                 </row>
853               </thead>
854               <tbody>
855                 <row>
856                   <entry morerows="1">First call to <function><link linkend="g-type-create-instance">g_type_create_instance</link></function> for type
857                     implementing interface
858                    </entry>
859                   <entry>interface' base_init function</entry>
860                   <entry>On interface' vtable</entry>
861                   <entry>Register interface' signals here (use a local static 
862                     boolean variable as described above to make sure not to register them
863                     twice.).</entry>
864                 </row>
865                 <row>
866                   <!--entry>First call to <function><link linkend="g-type-create-instance">g_type_create_instance</link></function> for type
867                     implementing interface
868                    </entry-->
869                   <entry>interface' interface_init function</entry>
870                   <entry>On interface' vtable</entry>
871                   <entry>
872                     Initialize interface' implementation. That is, initialize the interface 
873                     method pointers in the interface structure to the function's implementation.
874                   </entry>
875                 </row>
876               </tbody>
877             </tgroup>
878           </table>
879           It is highly unlikely (i.e. I do not know of <emphasis>anyone</emphasis> who actually 
880           used it) you will ever need other more fancy things such as the ones described in the
881           following section (<xref linkend="gtype-non-instantiable-classed-dest"/>).
882         </para>
883         
884         </sect2>
885         
886         <sect2 id="gtype-non-instantiable-classed-dest">
887           <title>Interface Destruction</title>
888
889           <para>
890             When the last instance of an instantiable type which registered 
891             an interface implementation is destroyed, the interface's 
892             implementations associated to the type are destroyed.
893           </para>
894
895           <para>
896             To destroy an interface implementation, GType first calls the 
897             implementation's <function>interface_finalize</function> function 
898             and then the interface's most-derived 
899             <function>base_finalize</function> function.
900           </para>
901
902           <para>
903             Again, it is important to understand, as in 
904             <xref linkend="gtype-non-instantiable-classed-init"/>,
905               that both <function>interface_finalize</function> and <function>base_finalize</function>
906               are invoked exactly once for the destruction of each implementation of an interface. Thus,
907               if you were to use one of these functions, you would need to use a static integer variable
908               which would hold the number of instances of implementations of an interface such that
909               the interface's class is destroyed only once (when the integer variable reaches zero).
910           </para>
911           
912         <para>
913           The above process can be summarized as follows:
914           <table id="ginterface-fini-table">
915             <title>Interface Finalization</title>
916             <tgroup cols="3">
917               <colspec colwidth="*" colnum="1" align="left"/>
918               <colspec colwidth="*" colnum="2" align="left"/>
919               <colspec colwidth="8*" colnum="3" align="left"/>
920               
921               <thead>
922                 <row>
923                   <entry>Invocation time</entry>
924                   <entry>Function Invoked</entry>
925                   <entry>Function's parameters</entry>
926                 </row>
927               </thead>
928               <tbody>
929                 <row>
930                   <entry morerows="1">Last call to <function><link linkend="g-type-free-instance">g_type_free_instance</link></function> for type
931                     implementing interface
932                    </entry>
933                   <entry>interface' interface_finalize function</entry>
934                   <entry>On interface' vtable</entry>
935                 </row>
936                 <row>
937                   <!--entry>Last call to <function><link linkend="g-type-free-instance">g_type_free_instance</link></function>for type
938                     implementing interface
939                    </entry-->
940                   <entry>interface' base_finalize function</entry>
941                   <entry>On interface' vtable</entry>
942                 </row>
943               </tbody>
944             </tgroup>
945           </table>
946         </para>
947       </sect2>
948     </sect1>
949   </chapter>