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