Tutorial
This chapter tries to answer the real-life questions of users and presents
the most common scenario use cases I could come up with.
The use cases are presented from most likely to less likely.
How to define and implement a new GObject
Clearly, this is one of the most common questions people ask: they just
want to crank code and implement a subclass of a GObject. Sometimes because
they want to create their own class hierarchy, sometimes because they want
to subclass one of GTK+'s widget. This chapter will focus on the
implementation of a subtype of GObject.
Boilerplate header code
The first step before writing the code for your GObject is to write the
type's header which contains the needed type, function and macro
definitions. Each of these elements is nothing but a convention which
is followed not only by GTK+'s code but also by most users of GObject.
If you feel the need not to obey the rules stated below, think about it
twice:
If your users are a bit accustomed to GTK+ code or any
GLib code, they will be a bit surprised and getting used to the
conventions you decided upon will take time (money) and will make them
grumpy (not a good thing)You must assess the fact that these conventions might
have been designed by both smart and experienced people: maybe they
were at least partly right. Try to put your ego aside.
Pick a name convention for your headers and source code and stick to it:
use a dash to separate the prefix from the typename:
maman-bar.h and maman-bar.c
(this is the convention used by Nautilus and most GNOME libraries).use an underscore to separate the prefix from the
typename: maman_bar.h and
maman_bar.c.Do not separate the prefix from the typename:
mamanbar.h and mamanbar.c.
(this is the convention used by GTK+)
Some people like the first two solutions better: it makes reading file
names easier for those with poor eyesight.
When you need some private (internal) declarations in several
(sub)classes, you can define them in a private header file which
is often named by appending the private keyword
to the public header name. For example, one could use
maman-bar-private.h,
maman_bar_private.h or
mamanbarprivate.h. Typically, such private header
files are not installed.
The basic conventions for any header which exposes a GType are described
in . Most GObject-based code also
obeys one of of the following conventions: pick one and stick to it.
If you want to declare a type named bar with prefix maman, name the type instance
MamanBar and its class MamanBarClass
(name is case-sensitive). It is customary to declare them with code similar to the
following:
/*
* Copyright/Licensing information.
*/
/* inclusion guard */
#ifndef __MAMAN_BAR_H__
#define __MAMAN_BAR_H__
#include <glib-object.h>
/*
* Potentially, include other headers on which this header depends.
*/
/*
* Type macros.
*/
#define MAMAN_TYPE_BAR (maman_bar_get_type ())
#define MAMAN_BAR(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_TYPE_BAR, MamanBar))
#define MAMAN_IS_BAR(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_TYPE_BAR))
#define MAMAN_BAR_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), MAMAN_TYPE_BAR, MamanBarClass))
#define MAMAN_IS_BAR_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), MAMAN_TYPE_BAR))
#define MAMAN_BAR_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), MAMAN_TYPE_BAR, MamanBarClass))
typedef struct _MamanBar MamanBar;
typedef struct _MamanBarClass MamanBarClass;
struct _MamanBar
{
GObject parent_instance;
/* instance members */
};
struct _MamanBarClass
{
GObjectClass parent_class;
/* class members */
};
/* used by MAMAN_TYPE_BAR */
GType maman_bar_get_type (void);
/*
* Method definitions.
*/
#endif /* __MAMAN_BAR_H__ */
Most GTK+ types declare their private fields in the public header
with a /* private */ comment, relying on their user's intelligence
not to try to play with these fields. Fields not marked private
are considered public by default. The /* protected */ comment
(same semantics as those of C++) is also used, mainly in the GType
library, in code written by Tim Janik.
struct _MamanBar
{
GObject parent_instance;
/*< private >*/
int hsize;
};
All of Nautilus code and a lot of GNOME libraries use private
indirection members, as described by Herb Sutter in his Pimpl
articles(see Compilation Firewalls
and The Fast Pimpl Idiom:
he summarizes the different issues better than I will).
typedef struct _MamanBarPrivate MamanBarPrivate;
struct _MamanBar
{
GObject parent_instance;
/*< private >*/
MamanBarPrivate *priv;
};
Do not call this private, as
that is a registered c++ keyword.
The private structure is then defined in the .c file, using the
g_type_class_add_private() function to notify the presence of
a private memory area for each instance and it can either
be retrieved using G_TYPE_INSTANCE_GET_PRIVATE()
each time is needed, or assigned to the priv
member of the instance structure inside the object's
init function.
#define MAMAN_BAR_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), MAMAN_TYPE_BAR, MamanBarPrivate))
struct _MamanBarPrivate
{
int hsize;
};
static void
maman_bar_class_init (MamanBarClass *klass)
{
g_type_class_add_private (klass, sizeof (MamanBarPrivate));
}
static void
maman_bar_init (MamanBar *self)
{
MamanBarPrivate *priv;
self->priv = priv = MAMAN_BAR_GET_PRIVATE (self);
priv->hsize = 42;
}
You don't need to free or allocate the private structure, only the
objects or pointers that it may contain. Another advantage of this
to the previous version is that is lessens memory fragmentation,
as the public and private parts of the instance memory are
allocated at once.
Finally, there are different header include conventions. Again, pick one
and stick to it. I personally use indifferently any of the two, depending
on the codebase I work on: the rule, as always, is consistency.
Some people add at the top of their headers a number of #include
directives to pull in all the headers needed to compile client
code. This allows client code to simply #include "maman-bar.h".
Other do not #include anything and expect the client to #include
themselves the headers they need before including your header. This
speeds up compilation because it minimizes the amount of
pre-processor work. This can be used in conjunction with the
re-declaration of certain unused types in the client code to
minimize compile-time dependencies and thus speed up compilation.
Boilerplate code
In your code, the first step is to #include the needed headers: depending
on your header include strategy, this can be as simple as
#include "maman-bar.h" or as complicated as tens
of #include lines ending with #include "maman-bar.h":
/*
* Copyright information
*/
#include "maman-bar.h"
/* If you use Pimpls, include the private structure
* definition here. Some people create a maman-bar-private.h header
* which is included by the maman-bar.c file and which contains the
* definition for this private structure.
*/
struct _MamanBarPrivate {
int member_1;
/* stuff */
};
/*
* forward definitions
*/
Call the G_DEFINE_TYPE macro using the name
of the type, the prefix of the functions and the parent GType to
reduce the amount of boilerplate needed. This macro will:
implement the maman_bar_get_type
functiondefine a parent class pointer accessible from
the whole .c file
G_DEFINE_TYPE (MamanBar, maman_bar, G_TYPE_OBJECT);
It is also possible to use the
G_DEFINE_TYPE_WITH_CODE macro to control the
get_type function implementation - for instance, to add a call to
G_IMPLEMENT_INTERFACE macro which will
call the g_type_implement_interface function.
Object Construction
People often get confused when trying to construct their GObjects because of the
sheer number of different ways to hook into the objects's construction process: it is
difficult to figure which is the correct, recommended way.
shows what user-provided functions
are invoked during object instantiation and in which order they are invoked.
A user looking for the equivalent of the simple C++ constructor function should use
the instance_init method. It will be invoked after all the parent's instance_init
functions have been invoked. It cannot take arbitrary construction parameters
(as in C++) but if your object needs arbitrary parameters to complete initialization,
you can use construction properties.
Construction properties will be set only after all instance_init functions have run.
No object reference will be returned to the client of g_object_new
until all the construction properties have been set.
As such, I would recommend writing the following code first:
static void
maman_bar_init (MamanBar *self)
{
self->priv = MAMAN_BAR_GET_PRIVATE (self);
/* initialize all public and private members to reasonable default values. */
/* If you need specific construction properties to complete initialization,
* delay initialization completion until the property is set.
*/
}
Now, if you need special construction properties, install the properties in the class_init function,
override the set and get methods and implement the get and set methods as described in
. Make sure that these properties use a construct only
GParamSpec by setting the param spec's flag field to G_PARAM_CONSTRUCT_ONLY: this helps
GType ensure that these properties are not set again later by malicious user code.
enum {
PROP_0,
PROP_MAMAN,
N_PROPERTIES
};
static GParamSpec *obj_properties[N_PROPERTIES] = { NULL, };
static void
bar_class_init (MamanBarClass *klass)
{
GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
gobject_class->set_property = bar_set_property;
gobject_class->get_property = bar_get_property;
obj_properties[PROP_MAMAN] =
g_param_spec_string ("maman",
"Maman construct prop",
"Set maman's name",
"no-name-set" /* default value */,
G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE);
g_object_class_install_properties (gobject_class,
N_PROPERTIES,
obj_properties);
}
If you need this, make sure you can build and run code similar to the code shown above. Make sure
your construct properties can set correctly during construction, make sure you cannot set them
afterwards and make sure that if your users do not call g_object_new
with the required construction properties, these will be initialized with the default values.
I consider good taste to halt program execution if a construction property is set its
default value. This allows you to catch client code which does not give a reasonable
value to the construction properties. Of course, you are free to disagree but you
should have a good reason to do so.
Some people sometimes need to construct their object but only after
the construction properties have been set. This is possible through
the use of the constructor class method as described in
or, more simply, using
the constructed class method available since GLib 2.12.
Object Destruction
Again, it is often difficult to figure out which mechanism to use to
hook into the object's destruction process: when the last
g_object_unref
function call is made, a lot of things happen as described in
.
The destruction process of your object might be split in two different
phases: dispose and the finalize.
#define MAMAN_BAR_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), MAMAN_TYPE_BAR, MamanBarPrivate))
struct _MamanBarPrivate
{
GObject *an_object;
gchar *a_string;
};
G_DEFINE_TYPE (MamanBar, maman_bar, G_TYPE_OBJECT);
static void
maman_bar_dispose (GObject *gobject)
{
MamanBar *self = MAMAN_BAR (gobject);
/*
* In dispose, you are supposed to free all types referenced from this
* object which might themselves hold a reference to self. Generally,
* the most simple solution is to unref all members on which you own a
* reference.
*/
/* dispose might be called multiple times, so we must guard against
* calling g_object_unref() on an invalid GObject.
*/
if (self->priv->an_object)
{
g_object_unref (self->priv->an_object);
self->priv->an_object = NULL;
}
/* Chain up to the parent class */
G_OBJECT_CLASS (maman_bar_parent_class)->dispose (gobject);
}
static void
maman_bar_finalize (GObject *gobject)
{
MamanBar *self = MAMAN_BAR (gobject);
g_free (self->priv->a_string);
/* Chain up to the parent class */
G_OBJECT_CLASS (maman_bar_parent_class)->finalize (gobject);
}
static void
maman_bar_class_init (MamanBarClass *klass)
{
GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
gobject_class->dispose = maman_bar_dispose;
gobject_class->finalize = maman_bar_finalize;
g_type_class_add_private (klass, sizeof (MamanBarPrivate));
}
static void
maman_bar_init (MamanBar *self);
{
self->priv = MAMAN_BAR_GET_PRIVATE (self);
self->priv->an_object = g_object_new (MAMAN_TYPE_BAZ, NULL);
self->priv->a_string = g_strdup ("Maman");
}
Add similar code to your GObject, make sure the code still builds
and runs: dispose and finalize must be called during the last unref.
It is possible that object methods might be invoked after dispose is
run and before finalize runs. GObject does not consider this to be a
program error: you must gracefully detect this and neither crash nor
warn the user.
Object methods
Just as with C++, there are many different ways to define object
methods and extend them: the following list and sections draw on
C++ vocabulary. (Readers are expected to know basic C++ buzzwords.
Those who have not had to write C++ code recently can refer to e.g.
to refresh
their memories.)
non-virtual public methods,
virtual public methods and
virtual private methods
Non-virtual public methods
These are the simplest: you want to provide a simple method which
can act on your object. All you need to do is to provide a function
prototype in the header and an implementation of that prototype
in the source file.
/* declaration in the header. */
void maman_bar_do_action (MamanBar *self, /* parameters */);
/* implementation in the source file */
void
maman_bar_do_action (MamanBar *self, /* parameters */)
{
g_return_if_fail (MAMAN_IS_BAR (self));
/* do stuff here. */
}
There is really nothing scary about this.Virtual public methods
This is the preferred way to create polymorphic GObjects. All you
need to do is to define the common method and its class function in
the public header, implement the common method in the source file
and re-implement the class function in each object which inherits
from you.
/* declaration in maman-bar.h. */
struct _MamanBarClass
{
GObjectClass parent_class;
/* stuff */
void (*do_action) (MamanBar *self, /* parameters */);
};
void maman_bar_do_action (MamanBar *self, /* parameters */);
/* implementation in maman-bar.c */
void
maman_bar_do_action (MamanBar *self, /* parameters */)
{
g_return_if_fail (MAMAN_IS_BAR (self));
MAMAN_BAR_GET_CLASS (self)->do_action (self, /* parameters */);
}
The code above simply redirects the do_action call to the relevant
class function. Some users, concerned about performance, do not
provide the maman_bar_do_action wrapper function
and require users to dereference the class pointer themselves. This
is not such a great idea in terms of encapsulation and makes it
difficult to change the object's implementation afterwards, should
this be needed.
Other users, also concerned by performance issues, declare
the maman_bar_do_action function inline in the
header file. This, however, makes it difficult to change the
object's implementation later (although easier than requiring users
to directly dereference the class function) and is often difficult
to write in a portable way (the inline keyword
is part of the C99 standard but not every compiler supports it).
In doubt, unless a user shows you hard numbers about the performance
cost of the function call, just implement maman_bar_do_action
in the source file.
Please, note that it is possible for you to provide a default
implementation for this class method in the object's
class_init function: initialize the
klass->do_action field to a pointer to the actual implementation.
You can also make this class method pure virtual by initializing
the klass->do_action field to NULL:
static void
maman_bar_real_do_action_two (MamanBar *self, /* parameters */)
{
/* Default implementation for the virtual method. */
}
static void
maman_bar_class_init (BarClass *klass)
{
/* pure virtual method: mandates implementation in children. */
klass->do_action_one = NULL;
/* merely virtual method. */
klass->do_action_two = maman_bar_real_do_action_two;
}
void
maman_bar_do_action_one (MamanBar *self, /* parameters */)
{
g_return_if_fail (MAMAN_IS_BAR (self));
MAMAN_BAR_GET_CLASS (self)->do_action_one (self, /* parameters */);
}
void
maman_bar_do_action_two (MamanBar *self, /* parameters */)
{
g_return_if_fail (MAMAN_IS_BAR (self));
MAMAN_BAR_GET_CLASS (self)->do_action_two (self, /* parameters */);
}
Virtual private Methods
These are very similar to Virtual Public methods. They just don't
have a public function to call the function directly. The header
file contains only a declaration of the class function:
/* declaration in maman-bar.h. */
struct _MamanBarClass
{
GObjectClass parent;
/* stuff */
void (* helper_do_specific_action) (MamanBar *self, /* parameters */);
};
void maman_bar_do_any_action (MamanBar *self, /* parameters */);
These class functions are often used to delegate part of the job
to child classes:
/* this accessor function is static: it is not exported outside of this file. */
static void
maman_bar_do_specific_action (MamanBar *self, /* parameters */)
{
MAMAN_BAR_GET_CLASS (self)->do_specific_action (self, /* parameters */);
}
void
maman_bar_do_any_action (MamanBar *self, /* parameters */)
{
/* random code here */
/*
* Try to execute the requested action. Maybe the requested action
* cannot be implemented here. So, we delegate its implementation
* to the child class:
*/
maman_bar_do_specific_action (self, /* parameters */);
/* other random code here */
}
Again, it is possible to provide a default implementation for this
private virtual class function:
static void
maman_bar_class_init (MamanBarClass *klass)
{
/* pure virtual method: mandates implementation in children. */
klass->do_specific_action_one = NULL;
/* merely virtual method. */
klass->do_specific_action_two = maman_bar_real_do_specific_action_two;
}
Children can then implement the subclass with code such as:
static void
maman_bar_subtype_class_init (MamanBarSubTypeClass *klass)
{
MamanBarClass *bar_class = MAMAN_BAR_CLASS (klass);
/* implement pure virtual class function. */
bar_class->do_specific_action_one = maman_bar_subtype_do_specific_action_one;
}
Chaining upChaining up is often loosely defined by the following set of
conditions:
Parent class A defines a public virtual method named foo and
provides a default implementation.Child class B re-implements method foo.In the method B::foo, the child class B calls its parent class method A::foo.
There are many uses to this idiom:
You need to change the behaviour of a class without modifying its code. You create
a subclass to inherit its implementation, re-implement a public virtual method to modify the behaviour
slightly and chain up to ensure that the previous behaviour is not really modified, just extended.
You are lazy, you have access to the source code of the parent class but you don't want
to modify it to add method calls to new specialized method calls: it is faster to hack the child class
to chain up than to modify the parent to call down.You need to implement the Chain Of Responsibility pattern: each object of the inheritance
tree chains up to its parent (typically, at the beginning or the end of the method) to ensure that
they each handler is run in turn.
I am personally not really convinced any of the last two uses are really a good idea but since this
programming idiom is often used, this section attempts to explain how to implement it.
To explicitly chain up to the implementation of the virtual method in the parent class,
you first need a handle to the original parent class structure. This pointer can then be used to
access the original class function pointer and invoke it directly.
The original adjective used in this sentence is not innocuous. To fully
understand its meaning, you need to recall how class structures are initialized: for each object type,
the class structure associated to this object is created by first copying the class structure of its
parent type (a simple memcpy) and then by invoking the class_init callback on
the resulting class structure. Since the class_init callback is responsible for overwriting the class structure
with the user re-implementations of the class methods, we cannot merely use the modified copy of the parent class
structure stored in our derived instance. We want to get a copy of the class structure of an instance of the parent
class.
The function g_type_class_peek_parent is used to access the original parent
class structure. Its input is a pointer to the class of the derived object and it returns a pointer
to the original parent class structure. The code below shows how you could use it:
static void
b_method_to_call (B *obj, int a)
{
BClass *klass;
AClass *parent_class;
klass = B_GET_CLASS (obj);
parent_class = g_type_class_peek_parent (klass);
/* do stuff before chain up */
parent_class->method_to_call (obj, a);
/* do stuff after chain up */
}
How to define and implement interfacesDefining interfaces
The bulk of interface definition has already been shown in
but I feel it is needed to show exactly how to create an interface.
As above, the first step is to get the header right. This interface
defines two methods:
#ifndef __MAMAN_IBAZ_H__
#define __MAMAN_IBAZ_H__
#include <glib-object.h>
#define MAMAN_TYPE_IBAZ (maman_ibaz_get_type ())
#define MAMAN_IBAZ(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_TYPE_IBAZ, MamanIbaz))
#define MAMAN_IS_IBAZ(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_TYPE_IBAZ))
#define MAMAN_IBAZ_GET_INTERFACE(inst) (G_TYPE_INSTANCE_GET_INTERFACE ((inst), MAMAN_TYPE_IBAZ, MamanIbazInterface))
typedef struct _MamanIbaz MamanIbaz; /* dummy object */
typedef struct _MamanIbazInterface MamanIbazInterface;
struct _MamanIbazInterface
{
GTypeInterface parent_iface;
void (*do_action) (MamanIbaz *self);
void (*do_something) (MamanIbaz *self);
};
GType maman_ibaz_get_type (void);
void maman_ibaz_do_action (MamanIbaz *self);
void maman_ibaz_do_something (MamanIbaz *self);
#endif /* __MAMAN_IBAZ_H__ */
This code is the same as the code for a normal GType
which derives from a GObject except for a few details:
The _GET_CLASS macro is called _GET_INTERFACE
and not implemented with G_TYPE_INSTANCE_GET_CLASS
but with G_TYPE_INSTANCE_GET_INTERFACE.
The instance type, MamanIbaz is not fully defined: it is
used merely as an abstract type which represents an instance of
whatever object which implements the interface.
The parent of the MamanIbazInterface is not
GObjectClass but GTypeInterface.
The implementation of the MamanIbaz type itself is trivial:
G_DEFINE_INTERFACE
creates a maman_ibaz_get_type function which registers the
type in the type system. The third argument is used to define a
prerequisite interface
(which we'll talk about more later). Just pass 0 for this
argument when an interface has no prerequisite.
maman_ibaz_default_init is expected
to register the interface's signals if there are any (we will see a bit
later how to use them).The interface methods maman_ibaz_do_action
and maman_ibaz_do_something dereference the interface
structure to access its associated interface function and call it.
G_DEFINE_INTERFACE (MamanIbaz, maman_ibaz, 0);
static void
maman_ibaz_default_init (gpointer g_class)
{
/* add properties and signals to the interface here */
}
void
maman_ibaz_do_action (MamanIbaz *self)
{
g_return_if_fail (MAMAN_IS_IBAZ (self));
MAMAN_IBAZ_GET_INTERFACE (self)->do_action (self);
}
void
maman_ibaz_do_something (MamanIbaz *self)
{
g_return_if_fail (MAMAN_IS_IBAZ (self));
MAMAN_IBAZ_GET_INTERFACE (self)->do_something (self);
}
Implementing interfaces
Once the interface is defined, implementing it is rather trivial.
The first step is to define a normal GObject class, like:
#ifndef __MAMAN_BAZ_H__
#define __MAMAN_BAZ_H__
#include <glib-object.h>
#define MAMAN_TYPE_BAZ (maman_baz_get_type ())
#define MAMAN_BAZ(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_TYPE_BAZ, Mamanbaz))
#define MAMAN_IS_BAZ(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_TYPE_BAZ))
#define MAMAN_BAZ_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), MAMAN_TYPE_BAZ, MamanbazClass))
#define MAMAN_IS_BAZ_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), MAMAN_TYPE_BAZ))
#define MAMAN_BAZ_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), MAMAN_TYPE_BAZ, MamanbazClass))
typedef struct _MamanBaz MamanBaz;
typedef struct _MamanBazClass MamanBazClass;
struct _MamanBaz
{
GObject parent_instance;
gint instance_member;
};
struct _MamanBazClass
{
GObjectClass parent_class;
};
GType maman_baz_get_type (void);
#endif /* __MAMAN_BAZ_H__ */
There is clearly nothing specifically weird or scary about this header:
it does not define any weird API or derive from a weird type.
The second step is to implement MamanBaz by defining
its GType. Instead of using
G_DEFINE_TYPE
we use
G_DEFINE_TYPE_WITH_CODE
and the
G_IMPLEMENT_INTERFACE
macros.
static void maman_ibaz_interface_init (MamanIbazInterface *iface);
G_DEFINE_TYPE_WITH_CODE (MamanBar, maman_bar, G_TYPE_OBJECT,
G_IMPLEMENT_INTERFACE (MAMAN_TYPE_IBAZ,
maman_ibaz_interface_init));
This definition is very much like all the similar functions we looked
at previously. The only interface-specific code present here is the call to
G_IMPLEMENT_INTERFACE.
Classes can implement multiple interfaces by using multiple calls to
G_IMPLEMENT_INTERFACE
inside the call to
G_DEFINE_TYPE_WITH_CODEmaman_baz_interface_init, the interface
initialization function: inside it every virtual method of the interface
must be assigned to its implementation:
static void
maman_baz_do_action (MamanBaz *self)
{
g_print ("Baz implementation of Ibaz interface Action: 0x%x.\n",
self->instance_member);
}
static void
maman_baz_do_something (MamanBaz *self)
{
g_print ("Baz implementation of Ibaz interface Something: 0x%x.\n",
self->instance_member);
}
static void
maman_ibaz_interface_init (MamanIbazInterface *iface)
{
iface->do_action = maman_baz_do_action;
iface->do_something = maman_baz_do_something;
}
static void
maman_baz_init (MamanBaz *self)
{
MamanBaz *self = MAMAN_BAZ (instance);
self->instance_member = 0xdeadbeaf;
}
Interface definition prerequisites
To specify that an interface requires the presence of other interfaces
when implemented, GObject introduces the concept of
prerequisites: it is possible to associate
a list of prerequisite types to an interface. For example, if
object A wishes to implement interface I1, and if interface I1 has a
prerequisite on interface I2, A has to implement both I1 and I2.
The mechanism described above is, in practice, very similar to
Java's interface I1 extends interface I2. The example below shows
the GObject equivalent:
/* Make the MamanIbar interface require MamanIbaz interface. */
G_DEFINE_INTERFACE (MamanIbar, maman_ibar, MAMAN_TYPE_IBAZ);
In the G_DEFINE_INTERFACE
call above, the third parameter defines the prerequisite type. This
is the GType of either an interface or a class. In this case
the MamanIbaz interface is a prerequisite of the MamanIbar. The code
below shows how an implementation can implement both interfaces and
register their implementations:
static void
maman_ibar_do_another_action (MamanIbar *ibar)
{
MamanBar *self = MAMAN_BAR (ibar);
g_print ("Bar implementation of IBar interface Another Action: 0x%x.\n",
self->instance_member);
}
static void
maman_ibar_interface_init (MamanIbarInterface *iface)
{
iface->do_another_action = maman_ibar_do_another_action;
}
static void
maman_ibaz_do_action (MamanIbaz *ibaz)
{
MamanBar *self = MAMAN_BAR (ibaz);
g_print ("Bar implementation of Ibaz interface Action: 0x%x.\n",
self->instance_member);
}
static void
maman_ibaz_do_something (MamanIbaz *ibaz)
{
MamanBar *self = MAMAN_BAR (ibaz);
g_print ("Bar implementation of Ibaz interface Something: 0x%x.\n",
self->instance_member);
}
static void
maman_ibaz_interface_init (MamanIbazInterface *iface)
{
iface->do_action = maman_ibaz_do_action;
iface->do_something = maman_ibaz_do_something;
}
static void
maman_bar_class_init (MamanBarClass *klass)
{
}
static void
maman_bar_init (MamanBar *self)
{
self->instance_member = 0x666;
}
G_DEFINE_TYPE_WITH_CODE (MamanBar, maman_bar, G_TYPE_OBJECT,
G_IMPLEMENT_INTERFACE (MAMAN_TYPE_IBAZ,
maman_ibaz_interface_init)
G_IMPLEMENT_INTERFACE (MAMAN_TYPE_IBAR,
maman_ibar_interface_init));
It is very important to notice that the order in which interface
implementations are added to the main object is not random:
g_type_add_interface_static,
which is called by
G_IMPLEMENT_INTERFACE,
must be invoked first on the interfaces which have no prerequisites and then on
the others.
Interface properties
GObject interfaces can also have
properties. Declaration of the interface properties is similar to
declaring the properties of ordinary GObject types as explained in
, except that
g_object_interface_install_property
is used to declare the properties instead of
g_object_class_install_property.
To include a property named 'name' of type string in the
maman_ibaz interface example code above, we only need to
add one
That really is one line extended to six for the sake of clarity
line in the maman_ibaz_default_init as shown below:
static void
maman_ibaz_default_init (gpointer g_iface)
{
g_object_interface_install_property (g_iface,
g_param_spec_string ("name",
"Name",
"Name of the MamanIbaz",
"maman",
G_PARAM_READWRITE));
}
One point worth noting is that the declared property wasn't assigned an
integer ID. The reason being that integer IDs of properties are used
only inside the get and set methods and since interfaces do not
implement properties, there is no need to assign integer IDs to
interface properties.
An implementation declares and defines it's properties in the usual
way as explained in , except for one
small change: it can declare the properties of the interface it
implements using g_object_class_override_property
instead of g_object_class_install_property.
The following code snippet shows the modifications needed in the
MamanBaz declaration and implementation above:
struct _MamanBaz
{
GObject parent_instance;
gint instance_member;
gchar *name;
};
enum
{
PROP_0,
PROP_NAME
};
static void
maman_baz_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
MamanBaz *baz = MAMAN_BAZ (object);
switch (prop_id)
{
case PROP_NAME:
g_free (baz->name);
baz->name = g_value_dup_string (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
maman_baz_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
MamanBaz *baz = MAMAN_BAZ (object);
switch (prop_id)
{
case PROP_NAME:
g_value_set_string (value, baz->name);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
maman_baz_class_init (MamanBazClass *klass)
{
GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
gobject_class->set_property = maman_baz_set_property;
gobject_class->get_property = maman_baz_get_property;
g_object_class_override_property (gobject_class, PROP_NAME, "name");
}
Overriding interface methods
If a base class already implements an interface, and in a derived
class you wish to implement the same interface overriding only certain
methods of that interface, you just reimplement the interface and
set only the interface methods you wish to override.
In this example MamanDerivedBaz is derived from MamanBaz. Both
implement the MamanIbaz interface. MamanDerivedBaz only implements one
method of the MamanIbaz interface and uses the base class implementation
of the other.
static void
maman_derived_ibaz_do_action (MamanIbaz *ibaz)
{
MamanDerivedBaz *self = MAMAN_DERIVED_BAZ (ibaz);
g_print ("DerivedBaz implementation of Ibaz interface Action\n");
}
static void
maman_derived_ibaz_interface_init (MamanIbazInterface *iface)
{
/* Override the implementation of do_action */
iface->do_action = maman_derived_ibaz_do_action;
/*
* We simply leave iface->do_something alone, it is already set to the
* base class implementation.
*/
}
G_DEFINE_TYPE_WITH_CODE (MamanDerivedBaz, maman_derived_baz, MAMAN_TYPE_BAZ,
G_IMPLEMENT_INTERFACE (MAMAN_TYPE_IBAZ,
maman_derived_ibaz_interface_init)
static void
maman_derived_baz_class_init (MamanDerivedBazClass *klass)
{
}
static void
maman_derived_baz_init (MamanDerivedBaz *self)
{
}
To access the base class interface implementation use
g_type_interface_peek_parent
from within an interface's default_init function.
If you wish to call the base class implementation of an interface
method from an derived class where than interface method has been
overridden then you can stash away the pointer returned from
g_type_interface_peek_parent
in a global variable.
In this example MamanDerivedBaz overides the
do_action interface method. In it's overridden method
it calls the base class implementation of the same interface method.
static MamanIbazInterface *maman_ibaz_parent_interface = NULL;
static void
maman_derived_ibaz_do_action (MamanIbaz *ibaz)
{
MamanDerivedBaz *self = MAMAN_DERIVED_BAZ (ibaz);
g_print ("DerivedBaz implementation of Ibaz interface Action\n");
/* Now we call the base implementation */
maman_ibaz_parent_interface->do_action (ibaz);
}
static void
maman_derived_ibaz_interface_init (MamanIbazInterface *iface)
{
maman_ibaz_parent_interface = g_type_interface_peek_parent (iface);
iface->do_action = maman_derived_ibaz_do_action;
}
G_DEFINE_TYPE_WITH_CODE (MamanDerivedBaz, maman_derived_baz, MAMAN_TYPE_BAZ,
G_IMPLEMENT_INTERFACE (MAMAN_TYPE_IBAZ,
maman_derived_ibaz_interface_init)
static void
maman_derived_baz_class_init (MamanDerivedBazClass *klass)
{
}
static void
maman_derived_baz_init (MamanDerivedBaz *self)
{
}
How to create and use signals
The signal system which was built in GType is pretty complex and
flexible: it is possible for its users to connect at runtime any
number of callbacks (implemented in any language for which a binding
exists)
A Python callback can be connected to any signal on any
C-based GObject.
to any signal and to stop the emission of any signal at any
state of the signal emission process. This flexibility makes it
possible to use GSignal for much more than just emit signals which
can be received by numerous clients.
Simple use of signals
The most basic use of signals is to implement simple event
notification: for example, if we have a MamanFile object, and
if this object has a write method, we might wish to be notified
whenever someone has changed something via our MamanFile instance.
The code below shows how the user can connect a callback to the
"changed" signal.
file = g_object_new (MAMAN_FILE_TYPE, NULL);
g_signal_connect (file, "changed", G_CALLBACK (changed_event), NULL);
maman_file_write (file, buffer, strlen (buffer));
The MamanFile signal is registered in the class_init
function:
file_signals[CHANGED] =
g_signal_newv ("changed",
G_TYPE_FROM_CLASS (gobject_class),
G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS,
NULL /* closure */,
NULL /* accumulator */,
NULL /* accumulator data */,
g_cclosure_marshal_VOID__VOID,
G_TYPE_NONE /* return_type */,
0 /* n_params */,
NULL /* param_types */);
and the signal is emitted in maman_file_write:
void
maman_file_write (MamanFile *self,
const guchar *buffer,
gssize size)
{
/* First write data. */
/* Then, notify user of data written. */
g_signal_emit (self, file_signals[CHANGED], 0 /* details */);
}
As shown above, you can safely set the details parameter to zero if
you do not know what it can be used for. For a discussion of what you
could used it for, see
The signature of the signal handler in the above example is defined as
g_cclosure_marshal_VOID__VOID. Its name follows
a simple convention which encodes the function parameter and return value
types in the function name. Specifically, the value in front of the
double underscore is the type of the return value, while the value(s)
after the double underscore denote the parameter types.
The header gobject/gmarshal.h defines a set of
commonly needed closures that one can use. If you want to have complex
marshallers for your signals you should probably use glib-genmarshal
to autogenerate them from a file containing their return and
parameter types.