GFile: add GBytes version of _replace_contents_async()
[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.5//EN" 
3                "http://www.oasis-open.org/docbook/xml/4.5/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, the type system not only initializes its
71         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         If you have no special requirements you can use the
326         <function><link linkend="G-DEFINE-TYPE:CAPS">G_DEFINE_TYPE</link></function>
327         macro to define a class:
328 <programlisting>
329 G_DEFINE_TYPE (MamanBar, maman_bar, G_TYPE_OBJECT)
330 </programlisting>
331       </para>
332
333       </sect1>
334
335       <sect1 id="gtype-non-instantiable">
336         <title>Non-instantiable non-classed fundamental types</title>
337
338         <para>
339           A lot of types are not instantiable by the type system and do not have
340           a class. Most of these types are fundamental trivial types such as <emphasis>gchar</emphasis>, 
341           registered in <function>_g_value_types_init</function> (in <filename>gvaluetypes.c</filename>).
342         </para>
343
344         <para>
345           To register such a type in the type system, you just need to fill the 
346           <link linkend="GTypeInfo"><type>GTypeInfo</type></link> structure with zeros since these types are also most of the time
347           fundamental:
348           <programlisting>
349   GTypeInfo info = {
350     0,                                /* class_size */
351     NULL,                        /* base_init */
352     NULL,                        /* base_destroy */
353     NULL,                        /* class_init */
354     NULL,                        /* class_destroy */
355     NULL,                        /* class_data */
356     0,                                /* instance_size */
357     0,                                /* n_preallocs */
358     NULL,                        /* instance_init */
359     NULL,                        /* value_table */
360   };
361   static const GTypeValueTable value_table = {
362     value_init_long0,                /* value_init */
363     NULL,                        /* value_free */
364     value_copy_long0,                /* value_copy */
365     NULL,                        /* value_peek_pointer */
366     "i",                        /* collect_format */
367     value_collect_int,        /* collect_value */
368     "p",                        /* lcopy_format */
369     value_lcopy_char,                /* lcopy_value */
370   };
371   info.value_table = &amp;value_table;
372   type = g_type_register_fundamental (G_TYPE_CHAR, "gchar", &amp;info, &amp;finfo, 0);
373           </programlisting>
374         </para>
375
376
377         <para>
378           Having non-instantiable types might seem a bit useless: what good is a type
379           if you cannot instantiate an instance of that type ? Most of these types
380           are used in conjunction with <link linkend="GValue"><type>GValue</type></link>s: a GValue is initialized
381           with an integer or a string and it is passed around by using the registered 
382           type's value_table. <link linkend="GValue"><type>GValue</type></link>s (and by extension these trivial fundamental
383           types) are most useful when used in conjunction with object properties and signals.
384         </para>
385
386       </sect1>
387
388       <sect1 id="gtype-instantiable-classed">
389         <title>Instantiable classed types: objects</title>
390
391         <para>
392           Types which are registered with a class and are declared instantiable are
393           what most closely resembles an <emphasis>object</emphasis>. 
394           Although <link linkend="GObject"><type>GObject</type></link>s (detailed in <xref linkend="chapter-gobject"/>) 
395           are the most well known type of instantiable
396           classed types, other kinds of similar objects used as the base of an inheritance 
397           hierarchy have been externally developed and they are all built on the fundamental
398           features described below.
399         </para>
400
401         <para>
402           For example, the code below shows how you could register 
403           such a fundamental object type in the type system:
404 <programlisting>
405 typedef struct {
406   GObject parent;
407   /* instance members */
408   int field_a;
409 } MamanBar;
410
411 typedef struct {
412   GObjectClass parent;
413   /* class members */
414   void (*do_action_public_virtual) (MamanBar *self, guint8 i);
415
416   void (*do_action_public_pure_virtual) (MamanBar *self, guint8 i);
417 } MamanBarClass;
418
419 #define MAMAN_TYPE_BAR (maman_bar_get_type ())
420
421 GType 
422 maman_bar_get_type (void)
423 {
424   static GType type = 0;
425   if (type == 0) {
426     const GTypeInfo info = {
427       sizeof (MamanBarClass),
428       NULL,           /* base_init */
429       NULL,           /* base_finalize */
430       (GClassInitFunc) foo_class_init,
431       NULL,           /* class_finalize */
432       NULL,           /* class_data */
433       sizeof (MamanBar),
434       0,              /* n_preallocs */
435       (GInstanceInitFunc) NULL /* instance_init */
436     };
437     type = g_type_register_static (G_TYPE_OBJECT,
438                                    "BarType",
439                                    &amp;info, 0);
440   }
441   return type;
442 }
443 </programlisting>
444           Upon the first call to <function>maman_bar_get_type</function>, the type named
445           <emphasis>BarType</emphasis> will be registered in the type system as inheriting
446           from the type <emphasis>G_TYPE_OBJECT</emphasis>.
447         </para>
448
449         <para>
450           Every object must define two structures: its class structure and its 
451           instance structure. All class structures must contain as first member
452           a <link linkend="GTypeClass"><type>GTypeClass</type></link> structure. All instance structures must contain as first
453           member a <link linkend="GTypeInstance"><type>GTypeInstance</type></link> structure. The declaration of these C types,
454           coming from <filename>gtype.h</filename> is shown below:
455 <programlisting>
456 struct _GTypeClass
457 {
458   GType g_type;
459 };
460 struct _GTypeInstance
461 {
462   GTypeClass *g_class;
463 };
464 </programlisting>
465           These constraints allow the type system to make sure that every object instance
466           (identified by a pointer to the object's instance structure) contains in its
467           first bytes a pointer to the object's class structure.
468         </para>
469         <para>
470           This relationship is best explained by an example: let's take object B which
471           inherits from object A:
472 <programlisting>
473 /* A definitions */
474 typedef struct {
475   GTypeInstance parent;
476   int field_a;
477   int field_b;
478 } A;
479 typedef struct {
480   GTypeClass parent_class;
481   void (*method_a) (void);
482   void (*method_b) (void);
483 } AClass;
484
485 /* B definitions. */
486 typedef struct {
487   A parent;
488   int field_c;
489   int field_d;
490 } B;
491 typedef struct {
492   AClass parent_class;
493   void (*method_c) (void);
494   void (*method_d) (void);
495 } BClass;
496 </programlisting>          
497           The C standard mandates that the first field of a C structure is stored starting
498           in the first byte of the buffer used to hold the structure's fields in memory.
499           This means that the first field of an instance of an object B is A's first field
500           which in turn is GTypeInstance's first field which in turn is g_class, a pointer
501           to B's class structure.
502         </para>
503
504         <para>
505           Thanks to these simple conditions, it is possible to detect the type of every
506           object instance by doing: 
507 <programlisting>
508 B *b;
509 b->parent.parent.g_class->g_type
510 </programlisting>
511           or, more quickly:
512 <programlisting>
513 B *b;
514 ((GTypeInstance*)b)->g_class->g_type
515 </programlisting>
516         </para>
517
518         <sect2 id="gtype-instantiable-classed-init-done">
519           <title>Initialization and Destruction</title>
520
521           <para>
522             instantiation of these types can be done with 
523             <function><link linkend="g-type-create-instance">g_type_create_instance</link></function>:
524 <programlisting>
525 GTypeInstance* g_type_create_instance (GType          type);
526 void           g_type_free_instance   (GTypeInstance *instance);
527 </programlisting>
528             <function><link linkend="g-type-create-instance">g_type_create_instance</link></function> will look up the type information
529             structure associated to the type requested. Then, the instance size and instantiation
530             policy (if the n_preallocs field is set to a non-zero value, the type system allocates
531             the object's instance structures in chunks rather than mallocing for every instance)
532             declared by the user are used to get a buffer to hold the object's instance
533             structure.
534           </para>
535
536           <para>
537             If this is the first instance of the object ever created, the type system must create a class structure.
538             It allocates a buffer to hold the object's class structure and initializes it. The first part of the
539             class structure (ie: the embedded parent class structure) is initialized by copying the contents from
540             the class structure of the parent class. The rest of class structure is initialized to zero.  If there
541             is no parent, the entire class structure is initialized to zero. The type system then invokes the
542             base_class_initialization functions (<link linkend="GBaseInitFunc"><type>GBaseInitFunc</type></link>) from topmost 
543             fundamental object to bottom-most most derived object. The object's class_init 
544             (<link linkend="GClassInitFunc"><type>GClassInitFunc</type></link>) function is invoked afterwards to complete
545             initialization of the class structure.
546             Finally, the object's interfaces are initialized (we will discuss interface initialization
547             in more detail later).
548           </para>
549
550           <para>
551             Once the type system has a pointer to an initialized class structure, it sets the object's
552             instance class pointer to the object's class structure and invokes the object's
553             instance_init (<link linkend="GInstanceInitFunc"><type>GInstanceInitFunc</type></link>)functions, from top-most fundamental 
554             type to bottom-most most derived type.
555           </para>
556
557           <para>
558             Object instance destruction through <function><link linkend="g-type-free-instance">g_type_free_instance</link></function> is very simple:
559             the instance structure is returned to the instance pool if there is one and if this was the
560             last living instance of the object, the class is destroyed.
561           </para>
562
563
564           <para>
565             Class destruction (the concept of destruction is sometimes partly 
566             referred to as finalization in GType) is the symmetric process of 
567             the initialization: interfaces are destroyed first. 
568             Then, the most derived 
569             class_finalize (<link linkend="GClassFinalizeFunc"><type>GClassFinalizeFunc</type></link>) function is invoked. The 
570             base_class_finalize (<link linkend="GBaseFinalizeFunc"><type>GBaseFinalizeFunc</type></link>) functions are 
571             Finally invoked from bottom-most most-derived type to top-most fundamental type and 
572             the class structure is freed.
573           </para>
574
575           <para>
576             As many readers have now understood it, the base initialization/finalization process is
577             very similar to the C++ constructor/destructor paradigm. The practical details are different
578             though and it is important not to get confused by superficial similarities. 
579             GTypes have no instance destruction mechanism. It is
580             the user's responsibility to implement correct destruction semantics on top
581             of the existing GType code. (this is what GObject does. See 
582             <xref linkend="chapter-gobject"/>)
583            Furthermore, C++ code equivalent to the base_init 
584            and class_init callbacks of GType is usually not needed because C++ cannot really create object 
585            types at runtime.
586           </para>
587
588           <para>
589             The instantiation/finalization process can be summarized as follows:
590             <table id="gtype-init-fini-table">
591               <title>GType Instantiation/Finalization</title>
592               <tgroup cols="3">
593                 <colspec colwidth="*" colnum="1" align="left"/>
594                 <colspec colwidth="*" colnum="2" align="left"/>
595                 <colspec colwidth="8*" colnum="3" align="left"/>
596     
597                 <thead>
598                   <row>
599                     <entry>Invocation time</entry>
600                     <entry>Function Invoked</entry>
601                     <entry>Function's parameters</entry>
602                   </row>
603                 </thead>
604                 <tbody>
605                   <row>
606                     <entry morerows="2">First call to <function><link linkend="g-type-create-instance">g_type_create_instance</link></function> for target type</entry>
607                     <entry>type's base_init function</entry>
608                     <entry>On the inheritance tree of classes from fundamental type to target type. 
609                       base_init is invoked once for each class structure.</entry>
610                   </row>
611                   <row>
612                     <!--entry>First call to <function><link linkend="g-type-create-instance">g_type_create_instance</link></function> for target type</entry-->
613                     <entry>target type's class_init function</entry>
614                     <entry>On target type's class structure</entry>
615                   </row>
616                   <row>
617                     <!--entry>First call to <function><link linkend="g-type-create-instance">g_type_create_instance</link></function> for target type</entry-->
618                     <entry>interface initialization, see 
619                       <xref linkend="gtype-non-instantiable-classed-init"/></entry>
620                     <entry></entry>
621                   </row>
622                   <row>
623                     <entry>Each call to <function><link linkend="g-type-create-instance">g_type_create_instance</link></function> for target type</entry>
624                     <entry>target type's instance_init function</entry>
625                     <entry>On object's instance</entry>
626                   </row>
627                   <row>
628                     <entry morerows="2">Last call to <function><link linkend="g-type-free-instance">g_type_free_instance</link></function> for target type</entry>
629                     <entry>interface destruction, see
630                       <xref linkend="gtype-non-instantiable-classed-dest"/></entry>
631                     <entry></entry>
632                   </row>
633                   <row>
634                     <!--entry>Last call to <function><link linkend="g-type-free-instance">g_type_free_instance</link></function> for target type</entry-->
635                     <entry>target type's class_finalize function</entry>
636                     <entry>On target type's class structure</entry>
637                   </row>
638                   <row>
639                     <!--entry>Last call to <function><link linkend="g-type-free-instance">g_type_free_instance</link></function> for target type</entry-->
640                     <entry>type's base_finalize function</entry>
641                     <entry>On the inheritance tree of classes from fundamental type to target type. 
642                       base_finalize is invoked once for each class structure.</entry>
643                   </row>
644                 </tbody>
645               </tgroup>
646             </table>
647           </para>
648           
649         </sect2>
650
651       </sect1>
652
653       <sect1 id="gtype-non-instantiable-classed">
654         <title>Non-instantiable classed types: interfaces</title>
655
656         <para>
657           GType's interfaces are very similar to Java's interfaces. They allow
658           to describe a common API that several classes will adhere to.
659           Imagine the play, pause and stop buttons on hi-fi equipment - those can
660           be seen as a playback interface. Once you know what they do, you can
661           control your CD player, MP3 player or anything that uses these symbols.
662           To declare an interface you have to register a non-instantiable
663           classed type which derives from 
664           <link linkend="GTypeInterface"><type>GTypeInterface</type></link>. The following piece of code declares such an interface.
665 <programlisting>
666 #define MAMAN_TYPE_IBAZ                (maman_ibaz_get_type ())
667 #define MAMAN_IBAZ(obj)                (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_TYPE_IBAZ, MamanIbaz))
668 #define MAMAN_IS_IBAZ(obj)             (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_TYPE_IBAZ))
669 #define MAMAN_IBAZ_GET_INTERFACE(inst) (G_TYPE_INSTANCE_GET_INTERFACE ((inst), MAMAN_TYPE_IBAZ, MamanIbazInterface))
670
671 typedef struct _MamanIbaz MamanIbaz; /* dummy object */
672 typedef struct _MamanIbazInterface MamanIbazInterface;
673
674 struct _MamanIbazInterface {
675   GTypeInterface parent;
676
677   void (*do_action) (MamanIbaz *self);
678 };
679
680 GType maman_ibaz_get_type (void);
681
682 void maman_ibaz_do_action (MamanIbaz *self);
683 </programlisting>
684           The interface function, <function>maman_ibaz_do_action</function> is implemented
685           in a pretty simple way:
686 <programlisting>
687 void maman_ibaz_do_action (MamanIbaz *self)
688 {
689   MAMAN_IBAZ_GET_INTERFACE (self)->do_action (self);
690 }
691 </programlisting>
692          <function>maman_ibaz_get_type</function> registers a type named <emphasis>MamanIbaz</emphasis>
693          which inherits from G_TYPE_INTERFACE. All interfaces must be children of G_TYPE_INTERFACE in the 
694          inheritance tree.
695         </para>
696
697         <para>
698           An interface is defined by only one structure which must contain as first member
699           a <link linkend="GTypeInterface"><type>GTypeInterface</type></link> structure. The interface structure is expected to
700           contain the function pointers of the interface methods. It is good style to 
701           define helper functions for each of the interface methods which simply call
702           the interface' method directly: <function>maman_ibaz_do_action</function>
703           is one of these.
704         </para>
705
706         <para>
707           Once an interface type is registered, you must register implementations for these
708           interfaces. The function named <function>maman_baz_get_type</function> registers
709           a new GType named MamanBaz which inherits from <link linkend="GObject"><type>GObject</type></link> and which
710           implements the interface <type>MamanIbaz</type>.
711 <programlisting>
712 static void maman_baz_do_action (MamanIbaz *self)
713 {
714   g_print ("Baz implementation of Ibaz interface Action.\n");
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 (MamanBazClass),
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
775         <para>
776         If you have no special requirements you can use the
777         <link linkend="G-IMPLEMENT-INTERFACE:CAPS">G_IMPLEMENT_INTERFACE</link> macro
778         to implement an interface:
779 <programlisting>
780 static void
781 maman_baz_do_action (MamanIbaz *self)
782 {
783   g_print ("Baz implementation of Ibaz interface Action.\n");
784 }
785
786 static void
787 maman_ibaz_interface_init (MamanIbazInterface *iface)
788 {
789   iface->do_action = maman_baz_do_action;
790 }
791
792 G_DEFINE_TYPE_WITH_CODE (MamanBaz, maman_baz, G_TYPE_OBJECT,
793                          G_IMPLEMENT_INTERFACE (MAMAN_TYPE_IBAZ,
794                                                 maman_ibaz_interface_init));
795 </programlisting>
796         </para>
797
798         <sect2 id="gtype-non-instantiable-classed-init">
799           <title>Interface Initialization</title>
800
801           <para>
802             When an instantiable classed type which implements an interface
803             (either directly or by inheriting an implementation from a superclass)
804             is created for the first time, its class structure is initialized
805             following the process described in <xref linkend="gtype-instantiable-classed"/>.
806             After that, the interface implementations associated with
807             the type are initialized.
808           </para>
809
810           <para>
811             First a memory buffer is allocated to hold the interface structure. The parent's
812             interface structure is then copied over to the new interface structure (the parent
813             interface is already initialized at that point). If there is no parent interface,
814             the interface structure is initialized with zeros. The g_type and the g_instance_type
815             fields are then initialized: g_type is set to the type of the most-derived interface
816             and g_instance_type is set to the type of the most derived type which implements 
817             this interface.
818           </para>
819
820           <para>
821             The interface's <function>base_init</function> function is called,
822             and then the interface's <function>default_init</function> is invoked.
823             Finally if the type has registered an implementation of the interface,
824             the implementation's <function>interface_init</function>
825             function is invoked. If there are multiple implementations of an
826             interface the <function>base_init</function> and
827             <function>interface_init</function> functions will be invoked once
828             for each implementation initialized.
829           </para>
830
831           <para>
832             It is thus recommended to use a <function>default_init</function> function to
833             initialize an interface. This function is called only once for the interface no
834             matter how many implementations there are. The
835             <function>default_init</function> function is declared by
836             <link linkend="G-DEFINE-INTERFACE:CAPS">G_DEFINE_INTERFACE</link>
837             which can be used to define the interface:
838 <programlisting>
839 G_DEFINE_INTERFACE (MamanIbaz, maman_ibaz, G_TYPE_OBJECT);
840
841 static void
842 maman_ibaz_default_init (MamanIbazInterface *iface)
843 {
844   /* add properties and signals here, will only called once */
845 }
846 </programlisting>
847           </para>
848
849           <para>
850             Or you can do that yourself in a GType function for your interface:
851 <programlisting>
852 GType
853 maman_ibaz_get_type (void)
854 {
855   static volatile gsize type_id = 0;
856   if (g_once_init_enter (&amp;type_id)) {
857     const GTypeInfo info = {
858       sizeof (MamanIbazInterface),
859       NULL,   /* base_init */
860       NULL,   /* base_finalize */
861       maman_ibaz_default_init, /* class_init */
862       NULL,   /* class_finalize */
863       NULL,   /* class_data */
864       0,      /* instance_size */
865       0,      /* n_preallocs */
866       NULL    /* instance_init */
867     };
868     GType type = g_type_register_static (G_TYPE_INTERFACE,
869                                         "MamanIbaz",
870                                         &amp;info, 0);
871     g_once_init_leave (&amp;type_id, type);
872   }
873   return type_id;
874 }
875
876 static void
877 maman_ibaz_default_init (MamanIbazInterface *iface)
878 {
879   /* add properties and signals here, will only called once */
880 }
881 </programlisting>
882           </para>
883
884         <para>
885           If you have found the stuff about interface hairy, you are right: it is hairy but
886           there is not much I can do about it. What I can do is summarize what you need to know
887           about interfaces:          
888         </para>
889
890           <para>
891           <table id="ginterface-init-table">
892             <title>Interface Initialization</title>
893             <tgroup cols="3">
894               <colspec colwidth="*" colnum="1" align="left"/>
895               <colspec colwidth="*" colnum="2" align="left"/>
896               <colspec colwidth="8*" colnum="3" align="left"/>
897               
898               <thead>
899                 <row>
900                   <entry>Invocation time</entry>
901                   <entry>Function Invoked</entry>
902                   <entry>Function's parameters</entry>
903                   <entry>Remark</entry>
904                 </row>
905               </thead>
906               <tbody>
907                 <row>
908                   <entry>First call to <function><link linkend="g-type-create-instance">g_type_create_instance</link></function>
909                     for <emphasis>any</emphasis> type implementing interface
910                    </entry>
911                   <entry>interface's <function>base_init</function> function</entry>
912                   <entry>On interface's vtable</entry>
913                   <entry>Rarely necessary to use this. Called once per instantiated classed type implementing the interface.</entry>
914                 </row>
915                 <row>
916                   <entry>First call to <function><link linkend="g-type-create-instance">g_type_create_instance</link></function>
917                     for <emphasis>each</emphasis> type implementing interface
918                    </entry>
919                   <entry>interface's <function>default_init</function> function</entry>
920                   <entry>On interface's vtable</entry>
921                   <entry>Register interface's signals, properties, etc. here. Will be called once.</entry>
922                 </row>
923                 <row>
924                   <entry>First call to <function><link linkend="g-type-create-instance">g_type_create_instance</link></function>
925                     for <emphasis>any</emphasis> type implementing interface
926                    </entry>
927                   <entry>implementation's <function>interface_init</function> function</entry>
928                   <entry>On interface's vtable</entry>
929                   <entry>
930                     Initialize interface implementation. Called for each class that that
931                     implements the interface. Initialize the interface method pointers
932                     in the interface structure to the implementing class's implementation.
933                   </entry>
934                 </row>
935               </tbody>
936             </tgroup>
937           </table>
938           It is highly unlikely (i.e. I do not know of <emphasis>anyone</emphasis> who actually 
939           used it) you will ever need other more fancy things such as the ones described in the
940           following section (<xref linkend="gtype-non-instantiable-classed-dest"/>).
941         </para>
942         
943         </sect2>
944         
945         <sect2 id="gtype-non-instantiable-classed-dest">
946           <title>Interface Destruction</title>
947
948           <para>
949             When the last instance of an instantiable type which registered 
950             an interface implementation is destroyed, the interface's 
951             implementations associated to the type are destroyed.
952           </para>
953
954           <para>
955             To destroy an interface implementation, GType first calls the 
956             implementation's <function>interface_finalize</function> function 
957             and then the interface's most-derived 
958             <function>base_finalize</function> function.
959           </para>
960
961           <para>
962             Again, it is important to understand, as in 
963             <xref linkend="gtype-non-instantiable-classed-init"/>,
964               that both <function>interface_finalize</function> and <function>base_finalize</function>
965               are invoked exactly once for the destruction of each implementation of an interface. Thus,
966               if you were to use one of these functions, you would need to use a static integer variable
967               which would hold the number of instances of implementations of an interface such that
968               the interface's class is destroyed only once (when the integer variable reaches zero).
969           </para>
970           
971         <para>
972           The above process can be summarized as follows:
973           <table id="ginterface-fini-table">
974             <title>Interface Finalization</title>
975             <tgroup cols="3">
976               <colspec colwidth="*" colnum="1" align="left"/>
977               <colspec colwidth="*" colnum="2" align="left"/>
978               <colspec colwidth="8*" colnum="3" align="left"/>
979               
980               <thead>
981                 <row>
982                   <entry>Invocation time</entry>
983                   <entry>Function Invoked</entry>
984                   <entry>Function's parameters</entry>
985                 </row>
986               </thead>
987               <tbody>
988                 <row>
989                   <entry morerows="1">Last call to <function><link linkend="g-type-free-instance">g_type_free_instance</link></function> for type
990                     implementing interface
991                    </entry>
992                   <entry>interface' interface_finalize function</entry>
993                   <entry>On interface' vtable</entry>
994                 </row>
995                 <row>
996                   <!--entry>Last call to <function><link linkend="g-type-free-instance">g_type_free_instance</link></function>for type
997                     implementing interface
998                    </entry-->
999                   <entry>interface' base_finalize function</entry>
1000                   <entry>On interface' vtable</entry>
1001                 </row>
1002               </tbody>
1003             </tgroup>
1004           </table>
1005         </para>
1006       </sect2>
1007     </sect1>
1008   </chapter>