# The GLib Dynamic Type System

A type, as manipulated by the GLib type system, is much more generic than what is usually understood as an Object type. It is best explained by looking at the structure and the functions used to register new types in the type system.

    typedef struct _GTypeInfo               GTypeInfo;
    struct _GTypeInfo
    {
      /* interface types, classed types, instantiated types */
      guint16                class_size;

      GBaseInitFunc          base_init;
      GBaseFinalizeFunc      base_finalize;

      /* classed types, instantiated types */
      GClassInitFunc         class_init;
      GClassFinalizeFunc     class_finalize;
      gconstpointer          class_data;

      /* instantiated types */
      guint16                instance_size;
      guint16                n_preallocs;
      GInstanceInitFunc      instance_init;

      /* value handling */
      const GTypeValueTable *value_table;
    };
    GType g_type_register_static (GType             parent_type,
                                  const gchar      *type_name,
                                  const GTypeInfo  *info,
                                  GTypeFlags        flags);
    GType g_type_register_fundamental (GType                       type_id,
                                       const gchar                *type_name,
                                       const GTypeInfo            *info,
                                       const GTypeFundamentalInfo *finfo,
                                       GTypeFlags                  flags);

`g_type_register_static`, `g_type_register_dynamic` and `g_type_register_fundamental` are the C functions, defined in `gtype.h` and implemented in `gtype.c` which you should use to register a new GType in the program's type system. It is not likely you will ever need to use `g_type_register_fundamental` but in case you want to, the last chapter explains how to create new fundamental types.

Fundamental types are top-level types which do not derive from any other type while other non-fundamental types derive from other types. Upon initialization, the type system not only initializes its internal data structures but it also registers a number of core types: some of these are fundamental types. Others are types derived from these fundamental types.

Fundamental and non-fundamental types are defined by:

- class size: the class_size field in GTypeInfo.

- class initialization functions (C++ constructor): the `base_init` and `class_init` fields in GTypeInfo.

- class destruction functions (C++ destructor): the base_finalize and class_finalize fields in GTypeInfo.

- instance size (C++ parameter to new): the instance_size field in GTypeInfo.

- instantiation policy (C++ type of new operator): the n_preallocs field in GTypeInfo.

- copy functions (C++ copy operators): the value_table field in GTypeInfo.

- type characteristic flags: GTypeFlags.

Fundamental types are also defined by a set of GTypeFundamentalFlags which are stored in a GTypeFundamentalInfo. Non-fundamental types are furthermore defined by the type of their parent which is passed as the parent_type parameter to `g_type_register_static` and `g_type_register_dynamic`.

## Copy functions

The major common point between all GLib types (fundamental and non-fundamental, classed and non-classed, instantiable and non-instantiable) is that they can all be manipulated through a single API to copy/assign them.

The GValue structure is used as an abstract container for all of these types. Its simplistic API (defined in `gobject/gvalue.h`) can be used to invoke the value_table functions registered during type registration: for example `g_value_copy` copies the content of a GValue to another GValue. This is similar to a C++ assignment which invokes the C++ copy operator to modify the default bit-by-bit copy semantics of C++/C structures/classes.

The following code shows how you can copy around a 64 bit integer, as well as a GObject instance pointer:

    static void test_int (void)
    {
      GValue a_value = G_VALUE_INIT;
      GValue b_value = G_VALUE_INIT;
      guint64 a, b;

      a = 0xdeadbeef;

      g_value_init (&a_value, G_TYPE_UINT64);
      g_value_set_uint64 (&a_value, a);

      g_value_init (&b_value, G_TYPE_UINT64);
      g_value_copy (&a_value, &b_value);

      b = g_value_get_uint64 (&b_value);

      if (a == b) {
        g_print ("Yay !! 10 lines of code to copy around a uint64.\n");
      } else {
        g_print ("Are you sure this is not a Z80 ?\n");
      }
    }

    static void test_object (void)
    {
      GObject *obj;
      GValue obj_vala = G_VALUE_INIT;
      GValue obj_valb = G_VALUE_INIT;
      obj = g_object_new (MAMAN_TYPE_BAR, NULL);

      g_value_init (&obj_vala, MAMAN_TYPE_BAR);
      g_value_set_object (&obj_vala, obj);

      g_value_init (&obj_valb, G_TYPE_OBJECT);

      /* g_value_copy's semantics for G_TYPE_OBJECT types is to copy the reference.
       * This function thus calls g_object_ref.
       * It is interesting to note that the assignment works here because
       * MAMAN_TYPE_BAR is a G_TYPE_OBJECT.
       */
      g_value_copy (&obj_vala, &obj_valb);

      g_object_unref (G_OBJECT (obj));
      g_object_unref (G_OBJECT (obj));
    }

The important point about the above code is that the exact semantics of the copy calls is undefined since they depend on the implementation of the copy function. Certain copy functions might decide to allocate a new chunk of memory and then to copy the data from the source to the destination. Others might want to simply increment the reference count of the instance and copy the reference to the new GValue.

The value table used to specify these assignment functions is documented in GTypeValueTable.

Interestingly, it is also very unlikely you will ever need to specify a value_table during type registration because these value_tables are inherited from the parent types for non-fundamental types.

## Conventions

There are a number of conventions users are expected to follow when creating new types which are to be exported in a header file:

- Type names (including object names) must be at least three characters long and start with ‘a–z’, ‘A–Z’ or ‘_’.

- Use the `object_method` pattern for function names: to invoke the method named foo on an instance of object type bar, call `bar_foo`.

- Use prefixing to avoid namespace conflicts with other projects. If your library (or application) is named Maman,

  Maman is the French word for mum or mother — nothing more and nothing less.

  prefix all your function names with maman_. For example: `maman_object_method`.

- Create a macro named `PREFIX_TYPE_OBJECT` which always returns the GType for the associated object type. For an object of type Bar in a library prefixed by maman, use: `MAMAN_TYPE_BAR`. This macro is implemented using a function named `prefix_object_get_type`.

- Use `G_DECLARE_FINAL_TYPE` or `G_DECLARE_DERIVABLE_TYPE` to define various other conventional macros for your object:

  - `PREFIX_OBJECT (obj)`, which returns a pointer of type PrefixObject. This macro is used to enforce static type safety by doing explicit casts wherever needed. It also enforces dynamic type safety by doing runtime checks. It is possible to disable the dynamic type checks in production builds (see building GLib). For example, we would create `MAMAN_BAR (obj)` to keep the previous example.

  - `PREFIX_OBJECT_CLASS (klass)`, which is strictly equivalent to the previous casting macro: it does static casting with dynamic type checking of class structures. It is expected to return a pointer to a class structure of type PrefixObjectClass. An example is: `MAMAN_BAR_CLASS`.

  - `PREFIX_IS_BAR (obj)`, which returns a gboolean which indicates whether the input object instance pointer is non-NULL and of type BAR.

  - `PREFIX_IS_OBJECT_CLASS (klass)`, which returns a boolean if the input class pointer is a pointer to a class of type OBJECT.

  - `PREFIX_OBJECT_GET_CLASS (obj)`, which returns the class pointer associated to an instance of a given type. This macro is used for static and dynamic type safety purposes (just like the previous casting macros).

The implementation of these macros is pretty straightforward: a number of simple-to-use macros are provided in `gtype.h`. For the example we used above, we would write the following trivial code to declare the macros:

    #define MAMAN_TYPE_BAR maman_bar_get_type ()
    G_DECLARE_FINAL_TYPE (MamanBar, maman_bar, MAMAN, BAR, GObject)

Unless your code has special requirements, you can use the `G_DEFINE_TYPE` macro to define a class:

    G_DEFINE_TYPE (MamanBar, maman_bar, G_TYPE_OBJECT)

Otherwise, the `maman_bar_get_type` function must be implemented manually:

    GType maman_bar_get_type (void)
    {
      static GType type = 0;
      if (type == 0) {
        const GTypeInfo info = {
          /* You fill this structure. */
        };
        type = g_type_register_static (G_TYPE_OBJECT,
                                       "MamanBarType",
                                       &info, 0);
      }
      return type;
    }

## Non-instantiable non-classed fundamental types

A lot of types are not instantiable by the type system and do not have a class. Most of these types are fundamental trivial types such as gchar, and are already registered by GLib.

In the rare case of needing to register such a type in the type system, fill a GTypeInfo structure with zeros since these types are also most of the time fundamental:

      GTypeInfo info = {
        0,                                /* class_size */
        NULL,                        /* base_init */
        NULL,                        /* base_destroy */
        NULL,                        /* class_init */
        NULL,                        /* class_destroy */
        NULL,                        /* class_data */
        0,                                /* instance_size */
        0,                                /* n_preallocs */
        NULL,                        /* instance_init */
        NULL,                        /* value_table */
      };
      static const GTypeValueTable value_table = {
        value_init_long0,                /* value_init */
        NULL,                        /* value_free */
        value_copy_long0,                /* value_copy */
        NULL,                        /* value_peek_pointer */
        "i",                        /* collect_format */
        value_collect_int,        /* collect_value */
        "p",                        /* lcopy_format */
        value_lcopy_char,                /* lcopy_value */
      };
      info.value_table = &value_table;
      type = g_type_register_fundamental (G_TYPE_CHAR, "gchar", &info, &finfo, 0);

Having non-instantiable types might seem a bit useless: what good is a type if you cannot instantiate an instance of that type ? Most of these types are used in conjunction with GValues: a GValue is initialized with an integer or a string and it is passed around by using the registered type's value_table. GValues (and by extension these trivial fundamental types) are most useful when used in conjunction with object properties and signals.

## Instantiable classed types: objects

This section covers the theory behind objects. See for the recommended way to define a GObject.

Types which are registered with a class and are declared instantiable are what most closely resembles an object. Although GObjects (detailed in ) are the most well known type of instantiable classed types, other kinds of similar objects used as the base of an inheritance hierarchy have been externally developed and they are all built on the fundamental features described below.

For example, the code below shows how you could register such a fundamental object type in the type system (using none of the GObject convenience API):

    typedef struct {
      GObject parent;
      /* instance members */
      int field_a;
    } MamanBar;

    typedef struct {
      GObjectClass parent;
      /* class members */
      void (*do_action_public_virtual) (MamanBar *self, guint8 i);

      void (*do_action_public_pure_virtual) (MamanBar *self, guint8 i);
    } MamanBarClass;

    #define MAMAN_TYPE_BAR (maman_bar_get_type ())

    GType
    maman_bar_get_type (void)
    {
      static GType type = 0;
      if (type == 0) {
        const GTypeInfo info = {
          sizeof (MamanBarClass),
          NULL,           /* base_init */
          NULL,           /* base_finalize */
          (GClassInitFunc) foo_class_init,
          NULL,           /* class_finalize */
          NULL,           /* class_data */
          sizeof (MamanBar),
          0,              /* n_preallocs */
          (GInstanceInitFunc) NULL /* instance_init */
        };
        type = g_type_register_static (G_TYPE_OBJECT,
                                       "BarType",
                                       &info, 0);
      }
      return type;
    }

Upon the first call to `maman_bar_get_type`, the type named BarType will be registered in the type system as inheriting from the type G_TYPE_OBJECT.

Every object must define two structures: its class structure and its instance structure. All class structures must contain as first member a GTypeClass structure. All instance structures must contain as first member a GTypeInstance structure. The declaration of these C types, coming from `gtype.h` is shown below:

    struct _GTypeClass
    {
      GType g_type;
    };
    struct _GTypeInstance
    {
      GTypeClass *g_class;
    };

These constraints allow the type system to make sure that every object instance (identified by a pointer to the object's instance structure) contains in its first bytes a pointer to the object's class structure.

This relationship is best explained by an example: let's take object B which inherits from object A:

    /* A definitions */
    typedef struct {
      GTypeInstance parent;
      int field_a;
      int field_b;
    } A;
    typedef struct {
      GTypeClass parent_class;
      void (*method_a) (void);
      void (*method_b) (void);
    } AClass;

    /* B definitions. */
    typedef struct {
      A parent;
      int field_c;
      int field_d;
    } B;
    typedef struct {
      AClass parent_class;
      void (*method_c) (void);
      void (*method_d) (void);
    } BClass;

The C standard mandates that the first field of a C structure is stored starting in the first byte of the buffer used to hold the structure's fields in memory. This means that the first field of an instance of an object B is A's first field which in turn is GTypeInstance's first field which in turn is g_class, a pointer to B's class structure.

Thanks to these simple conditions, it is possible to detect the type of every object instance by doing:

    B *b;
    b->parent.parent.g_class->g_type

or, more quickly:

    B *b;
    ((GTypeInstance *) b)->g_class->g_type

### Initialization and Destruction

instantiation of these types can be done with `g_type_create_instance`, which will look up the type information structure associated with the type requested. Then, the instance size and instantiation policy (if the n_preallocs field is set to a non-zero value, the type system allocates the object's instance structures in chunks rather than mallocing for every instance) declared by the user are used to get a buffer to hold the object's instance structure.

If this is the first instance of the object ever created, the type system must create a class structure. It allocates a buffer to hold the object's class structure and initializes it. The first part of the class structure (ie: the embedded parent class structure) is initialized by copying the contents from the class structure of the parent class. The rest of class structure is initialized to zero. If there is no parent, the entire class structure is initialized to zero. The type system then invokes the `base_class_initialization` functions (GBaseInitFunc) from topmost fundamental object to bottom-most most derived object. The object's `class_init` (GClassInitFunc) function is invoked afterwards to complete initialization of the class structure. Finally, the object's interfaces are initialized (we will discuss interface initialization in more detail later).

Once the type system has a pointer to an initialized class structure, it sets the object's instance class pointer to the object's class structure and invokes the object's `instance_init` (GInstanceInitFunc) functions, from top-most fundamental type to bottom-most most-derived type.

Object instance destruction through `g_type_free_instance` is very simple: the instance structure is returned to the instance pool if there is one and if this was the last living instance of the object, the class is destroyed.

Class destruction (the concept of destruction is sometimes partly referred to as finalization in GType) is the symmetric process of the initialization: interfaces are destroyed first. Then, the most derived class_finalize (GClassFinalizeFunc) function is invoked. Finally, the base_class_finalize (GBaseFinalizeFunc) functions are invoked from bottom-most most-derived type to top-most fundamental type and the class structure is freed.

The base initialization/finalization process is very similar to the C++ constructor/destructor paradigm. The practical details are different though and it is important not to get confused by superficial similarities. GTypes have no instance destruction mechanism. It is the user's responsibility to implement correct destruction semantics on top of the existing GType code. (This is what GObject does: see .) Furthermore, C++ code equivalent to the `base_init` and `class_init` callbacks of GType is usually not needed because C++ cannot really create object types at runtime.

The instantiation/finalization process can be summarized as follows:

GType Instantiation/Finalization

Invocation time | Function invoked | Function's parameters
--- | --- | ---
First call to `g_type_create_instance` for target type | type's `base_init` function | On the inheritance tree of classes from fundamental type to target type. `base_init` is invoked once for each class structure.
target type's `class_init` function | On target type's class structure
interface initialization, see |
Each call to `g_type_create_instance` for target type | target type's `instance_init` function | On object's instance
Last call to `g_type_free_instance` for target type | interface destruction, see |
target type's `class_finalize` function | On target type's class structure
type's `base_finalize` function | On the inheritance tree of classes from fundamental type to target type. `base_finalize` is invoked once for each class structure.

## Non-instantiable classed types: interfaces

This section covers the theory behind interfaces. See for the recommended way to define an interface.

GType's interfaces are very similar to Java's interfaces. They allow to describe a common API that several classes will adhere to. Imagine the play, pause and stop buttons on hi-fi equipment — those can be seen as a playback interface. Once you know what they do, you can control your CD player, MP3 player or anything that uses these symbols. To declare an interface you have to register a non-instantiable classed type which derives from GTypeInterface. The following piece of code declares such an interface.

    #define MAMAN_TYPE_IBAZ maman_ibaz_get_type ()
    G_DECLARE_INTERFACE(MamanIbaz, maman_ibaz, MAMAN, IBAZ, GObject)

    struct _MamanIbazInterface {
      GTypeInterface parent;

      void (*do_action) (MamanIbaz *self);
    };

    void maman_ibaz_do_action (MamanIbaz *self);

The interface function, `maman_ibaz_do_action` is implemented in a pretty simple way:

    void maman_ibaz_do_action (MamanIbaz *self)
    {
      g_return_if_fail (MAMAN_IS_IBAZ (self));

      MAMAN_IBAZ_GET_INTERFACE (self)->do_action (self);
    }

`maman_ibaz_get_type` registers a type named MamanIbaz which inherits from G_TYPE_INTERFACE. All interfaces must be children of G_TYPE_INTERFACE in the inheritance tree.

An interface is defined by only one structure which must contain as first member a GTypeInterface structure. The interface structure is expected to contain the function pointers of the interface methods. It is good style to define helper functions for each of the interface methods which simply call the interface's method directly: `maman_ibaz_do_action` is one of these.

If you have no special requirements you can use the G_IMPLEMENT_INTERFACE macro to implement an interface:

    static void
    maman_baz_do_action (MamanIbaz *self)
    {
      g_print ("Baz implementation of Ibaz interface Action.\n");
    }

    static void
    maman_ibaz_interface_init (MamanIbazInterface *iface)
    {
      iface->do_action = maman_baz_do_action;
    }

    G_DEFINE_TYPE_WITH_CODE (MamanBaz, maman_baz, G_TYPE_OBJECT,
                             G_IMPLEMENT_INTERFACE (MAMAN_TYPE_IBAZ,
                                                    maman_ibaz_interface_init));

If your code does have special requirements, you must write a custom `get_type` function to register your GType which inherits from some GObject and which implements the interface MamanIbaz. For example, this code registers a new MamanBaz class which implements MamanIbaz:

    static void
    maman_baz_do_action (MamanIbaz *self)
    {
      g_print ("Baz implementation of Ibaz interface Action.\n");
    }

    static void
    baz_interface_init (gpointer         g_iface,
                        gpointer         iface_data)
    {
      MamanIbazInterface *iface = (MamanIbazInterface *)g_iface;
      iface->do_action = maman_baz_do_action;
    }

    GType
    maman_baz_get_type (void)
    {
      static GType type = 0;
      if (type == 0) {
        const GTypeInfo info = {
          sizeof (MamanBazClass),
          NULL,   /* base_init */
          NULL,   /* base_finalize */
          NULL,   /* class_init */
          NULL,   /* class_finalize */
          NULL,   /* class_data */
          sizeof (MamanBaz),
          0,      /* n_preallocs */
          NULL    /* instance_init */
        };
        const GInterfaceInfo ibaz_info = {
          (GInterfaceInitFunc) baz_interface_init,    /* interface_init */
          NULL,               /* interface_finalize */
          NULL          /* interface_data */
        };
        type = g_type_register_static (G_TYPE_OBJECT,
                                       "MamanBazType",
                                       &info, 0);
        g_type_add_interface_static (type,
                                     MAMAN_TYPE_IBAZ,
                                     &ibaz_info);
      }
      return type;
    }

`g_type_add_interface_static` records in the type system that a given type implements also FooInterface (`foo_interface_get_type` returns the type of FooInterface). The GInterfaceInfo structure holds information about the implementation of the interface:

    struct _GInterfaceInfo
    {
      GInterfaceInitFunc     interface_init;
      GInterfaceFinalizeFunc interface_finalize;
      gpointer               interface_data;
    };

### Interface Initialization

When an instantiable classed type which implements an interface (either directly or by inheriting an implementation from a superclass) is created for the first time, its class structure is initialized following the process described in . After that, the interface implementations associated with the type are initialized.

First a memory buffer is allocated to hold the interface structure. The parent's interface structure is then copied over to the new interface structure (the parent interface is already initialized at that point). If there is no parent interface, the interface structure is initialized with zeros. The g_type and the g_instance_type fields are then initialized: g_type is set to the type of the most-derived interface and g_instance_type is set to the type of the most derived type which implements this interface.

The interface's `base_init` function is called, and then the interface's `default_init` is invoked. Finally if the type has registered an implementation of the interface, the implementation's `interface_init` function is invoked. If there are multiple implementations of an interface the `base_init` and `interface_init` functions will be invoked once for each implementation initialized.

It is thus recommended to use a `default_init` function to initialize an interface. This function is called only once for the interface no matter how many implementations there are. The `default_init` function is declared by G_DEFINE_INTERFACE which can be used to define the interface:

    G_DEFINE_INTERFACE (MamanIbaz, maman_ibaz, G_TYPE_OBJECT);

    static void
    maman_ibaz_default_init (MamanIbazInterface *iface)
    {
      /* add properties and signals here, will only called once */
    }

Or you can do that yourself in a GType function for your interface:

    GType
    maman_ibaz_get_type (void)
    {
      static volatile gsize type_id = 0;
      if (g_once_init_enter (&type_id)) {
        const GTypeInfo info = {
          sizeof (MamanIbazInterface),
          NULL,   /* base_init */
          NULL,   /* base_finalize */
          maman_ibaz_default_init, /* class_init */
          NULL,   /* class_finalize */
          NULL,   /* class_data */
          0,      /* instance_size */
          0,      /* n_preallocs */
          NULL    /* instance_init */
        };
        GType type = g_type_register_static (G_TYPE_INTERFACE,
                                            "MamanIbaz",
                                            &info, 0);
        g_once_init_leave (&type_id, type);
      }
      return type_id;
    }

    static void
    maman_ibaz_default_init (MamanIbazInterface *iface)
    {
      /* add properties and signals here, will only called once */
    }

In summary, interface initialization uses the following functions:

Interface Initialization

Invocation time | Function Invoked | Function's parameters | Remark
--- | --- | --- | ---
First call to `g_type_create_instance` for any type implementing interface | interface's `base_init` function | On interface's vtable | Rarely necessary to use this. Called once per instantiated classed type implementing the interface.
First call to `g_type_create_instance` for each type implementing interface | interface's `default_init` function | On interface's vtable | Register interface's signals, properties, etc. here. Will be called once.
First call to `g_type_create_instance` for any type implementing interface | implementation's `interface_init` function | On interface's vtable | Initialize interface implementation. Called for each class that that implements the interface. Initialize the interface method pointers in the interface structure to the implementing class's implementation.

### Interface Destruction

When the last instance of an instantiable type which registered an interface implementation is destroyed, the interface's implementations associated to the type are destroyed.

To destroy an interface implementation, GType first calls the implementation's `interface_finalize` function and then the interface's most-derived `base_finalize` function.

Again, it is important to understand, as in , that both `interface_finalize` and `base_finalize` are invoked exactly once for the destruction of each implementation of an interface. Thus, if you were to use one of these functions, you would need to use a static integer variable which would hold the number of instances of implementations of an interface such that the interface's class is destroyed only once (when the integer variable reaches zero).

The above process can be summarized as follows:

Interface Finalization

Invocation time | Function Invoked | Function's parameters
--- | --- | ---
Last call to `g_type_free_instance` for type implementing interface | interface's `interface_finalize` function | On interface's vtable
interface's `base_finalize` function | On interface's vtable