From 33129dca91e93726b5ef7ffa99b9222a2520c70a Mon Sep 17 00:00:00 2001 From: Mathieu Lacage Date: Thu, 10 Jun 2004 09:41:43 +0000 Subject: [PATCH] add chain up section --- docs/reference/gobject/tut_howto.xml | 990 ++++++++++++++++++----------------- 1 file changed, 510 insertions(+), 480 deletions(-) diff --git a/docs/reference/gobject/tut_howto.xml b/docs/reference/gobject/tut_howto.xml index 87290d9..98e8f87 100644 --- a/docs/reference/gobject/tut_howto.xml +++ b/docs/reference/gobject/tut_howto.xml @@ -41,52 +41,52 @@ 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. - - + 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+) - - - I personally like the first solution better: it makes reading file names easier for those with poor - eyesight like me. + 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+) + + + I personally like the first solution better: it makes reading file names easier for those with poor + eyesight like me. - The basic conventions for any header which exposes a GType are described in - . Most GObject-based code also obeys onf 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: + The basic conventions for any header which exposes a GType are described in + . Most GObject-based code also obeys onf 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. @@ -108,13 +108,13 @@ typedef struct _MamanBar MamanBar; typedef struct _MamanBarClass MamanBarClass; struct _MamanBar { - GObject parent; - /* instance members */ + GObject parent; + /* instance members */ }; struct _MamanBarClass { - GObjectClass parent; - /* class members */ + GObjectClass parent; + /* class members */ }; /* used by MAMAN_BAR_TYPE */ @@ -126,68 +126,68 @@ GType maman_bar_get_type (void); #endif - - - 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. + + + 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; - - /* private */ - int hsize; + GObject parent; + + /* 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 : Herb summarizes the different - issues better than I will): + + + All of Nautilus code and a lot of Gnome libraries use private indirection members, as described + by Herb Sutter in his Pimpl articles (see : Herb summarizes the different + issues better than I will): typedef struct _MamanBarPrivate MamanBarPrivate; struct _MamanBar { - GObject parent; + GObject parent; - /* private */ - MamanBarPrivate *priv; + /* private */ + MamanBarPrivate *priv; }; - The private structure is then defined in the .c file, instantiated in the object's XXX - function and destroyed in the object's XXX function. - - + The private structure is then defined in the .c file, instantiated in the object's XXX + function and destroyed in the object's XXX function. + + - 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 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. - - + 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 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": + 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 @@ -201,8 +201,8 @@ struct _MamanBar { * definition for this private structure. */ struct _MamanBarPrivate { - int member_1; - /* stuff */ + int member_1; + /* stuff */ }; /* @@ -212,27 +212,27 @@ struct _MamanBarPrivate { - Implement maman_bar_get_type and make sure the code compiles: + Implement maman_bar_get_type and make sure the code compiles: GType maman_bar_get_type (void) { - static GType type = 0; - if (type == 0) { - static const GTypeInfo info = { - sizeof (MamanBarClass), - NULL, /* base_init */ - NULL, /* base_finalize */ - NULL, /* class_init */ - NULL, /* class_finalize */ - NULL, /* class_data */ - sizeof (MamanBar), - 0, /* n_preallocs */ - NULL /* instance_init */ + static GType type = 0; + if (type == 0) { + static const GTypeInfo info = { + sizeof (MamanBarClass), + NULL, /* base_init */ + NULL, /* base_finalize */ + NULL, /* class_init */ + NULL, /* class_finalize */ + NULL, /* class_data */ + sizeof (MamanBar), + 0, /* n_preallocs */ + NULL /* instance_init */ }; type = g_type_register_static (G_TYPE_OBJECT, - "MamanBarType", - &info, 0); + "MamanBarType", + &info, 0); } return type; } @@ -244,29 +244,29 @@ maman_bar_get_type (void) 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. + 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 instanciation 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. + shows what user-provided functions + are invoked during object instanciation 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. + 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: + As such, I would recommend writing the following code first: static void maman_bar_init (GTypeInstance *instance, @@ -275,24 +275,24 @@ maman_bar_init (GTypeInstance *instance, MamanBar *self = (MamanBar *)instance; self->private = g_new0 (MamanBarPrivate, 1); - /* initialize all public and private members to reasonable default values. */ - /* If you need specific consruction properties to complete initialization, - * delay initialization completion until the property is set. - */ + /* initialize all public and private members to reasonable default values. */ + /* If you need specific consruction properties to complete initialization, + * delay initialization completion until the property is set. + */ } - And make sure that you set maman_bar_init as the type's instance_init function - in maman_bar_get_type. Make sure the code builds and runs: create an instance - of the object and make sure maman_bar_init is called (add a - g_print call in it). + And make sure that you set maman_bar_init as the type's instance_init function + in maman_bar_get_type. Make sure the code builds and runs: create an instance + of the object and make sure maman_bar_init is called (add a + g_print call in it). - 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. + 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. static void bar_class_init (MamanBarClass *klass) @@ -310,43 +310,43 @@ bar_class_init (MamanBarClass *klass) G_PARAM_CONSTRUCT_ONLY |G_PARAM_READWRITE); g_object_class_install_property (gobject_class, - PROP_MAMAN, - maman_param_spec); + PROP_MAMAN, + maman_param_spec); } - 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. + 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. + 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 - . However, I have yet to see any reasonable - use of this feature. As such, to initialize your object instances, use by default the base_init function - and construction properties. - + 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 + . However, I have yet to see any reasonable + use of this feature. As such, to initialize your object instances, use by default the base_init function + and construction properties. + 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 . + 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 must be split is two different phases: you must override - both the dispose and the finalize class methods. + The destruction process of your object must be split is two different phases: you must override + both the dispose and the finalize class methods. struct _MamanBarPrivate { gboolean dispose_has_run; @@ -377,7 +377,7 @@ bar_finalize (MamanBar *self) * Here, complete object destruction. * You might not need to do much... */ - g_free (self->private); + g_free (self->private); } static void @@ -401,12 +401,12 @@ maman_bar_init (GTypeInstance *instance, - 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. To do this, you need something like the following code at the start of each object method, to make - sure the object's data is still valid before manipulating it: + 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. To do this, you need something like the following code at the start of each object method, to make + sure the object's data is still valid before manipulating it: if (self->private->dispose_has_run) { /* Dispose has run. Data is not valid anymore. */ @@ -420,31 +420,31 @@ if (self->private->dispose_has_run) { 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 XXXX to refresh their - memories.) - - - non-virtual public methods, - - - virtual public methods and - - - virtual private 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 XXXX to refresh their + memories.) + + + non-virtual public methods, + + + virtual public methods and + + + virtual private methods + + - Non-virtual public 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. + + 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 */); @@ -454,19 +454,19 @@ void maman_bar_do_action (MamanBar *self, /* parameters */) /* do stuff here. */ } - + - There is really nothing scary about this. + There is really nothing scary about this. - Virtual public methods + 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. + + 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 { @@ -479,68 +479,68 @@ void maman_bar_do_action (MamanBar *self, /* parameters */); /* implementation in maman-bar.c */ void maman_bar_do_action (MamanBar *self, /* parameters */) { - MAMAN_BAR_GET_CLASS (self)->do_action (self, /* parameters */); + 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 de-reference 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 de-reference the class - function) and is often difficult to write in a portable way (the inline keyword - is not part of the C standard). - - - - In doubt, unless a user shows you hard numbers about the performance cost of the function call, - just 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: + 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 de-reference 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 de-reference the class + function) and is often difficult to write in a portable way (the inline keyword + is not part of the C standard). + + + + In doubt, unless a user shows you hard numbers about the performance cost of the function call, + just 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. */ + /* 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; + /* 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 */) { - MAMAN_BAR_GET_CLASS (self)->do_action_one (self, /* parameters */); + MAMAN_BAR_GET_CLASS (self)->do_action_one (self, /* parameters */); } void maman_bar_do_action_two (MamanBar *self, /* parameters */) { - MAMAN_BAR_GET_CLASS (self)->do_action_two (self, /* parameters */); + MAMAN_BAR_GET_CLASS (self)->do_action_two (self, /* parameters */); } - + - Virtual private Methods + 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: + + 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 { @@ -551,13 +551,13 @@ struct _MamanBarClass { }; void maman_bar_do_any_action (MamanBar *self, /* parameters */); - These class functions are often used to delegate part of the job to child classes: + 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 */); + MAMAN_BAR_GET_CLASS (self)->do_specific_action (self, /* parameters */); } void maman_bar_do_any_action (MamanBar *self, /* parameters */) @@ -568,77 +568,107 @@ void maman_bar_do_any_action (MamanBar *self, /* parameters */) * 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 */); + 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: + + 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; + /* 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; } - + - - Finally, it is interesting to note that, just like in C++, it is possible - to make each object class method chain to its parent class method: + + Children can then implement the subclass with code such as: -static void -maman_bar_real_do_action_two (MamanBar *self, /* parameters */) -{ - MamanBarClass *bar_class = g_type_class_peek_parent (klass); - /* chain up */ - bar_class->do_action (self, /* parameters */); - - /* do local stuff here. */ -} - 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; + 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 up -

Chaining up is commonly used to implement the Chain Of Responsability pattern in C++: each class in a - given inheritance hierarchy is expected to override the same method and then call from within each method - the overriden method of the parent. Personally, I am not sure this is a very smart idea (a detailed explanation - of why I think it is a bad idea would take too much space for this document) but I can show you how to do it and - here is an example. -

+ Chaining up is often loosely defined by the folowing 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 modifed, 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 Responsability pattern: each object of the inheritance + tree chains up to its parent (typically, at the begining 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 attemps to explain how to implement it. + + + To explicitely 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. + + + -

To invoke the parent method XXX

+ 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 */ +} + + A lot of people who use this idiom in GTK+ store the parent class structure pointer in a global static + variable to avoid the costly call to g_type_class_peek_parent for each function call. + Typically, the class_init callback initializes the global static variable. gtk/gtkhscale.c + does this. +
@@ -686,16 +716,16 @@ typedef struct _MamanIbaz MamanIbaz; /* dummy object */ typedef struct _MamanIbazClass MamanIbazClass; struct _MamanIbazClass { - GTypeInterface parent; + GTypeInterface parent; - void (*do_action) (MamanIbaz *self); + void (*do_action) (MamanIbaz *self); }; GType maman_ibaz_get_type (void); void maman_ibaz_do_action (MamanIbaz *self); -#endif //MAMAN_IBAZ_H +#endif /*MAMAN_IBAZ_H*/ This code is almost exactly similar to the code for a normal GType which derives from a GObject except for a few details: @@ -732,38 +762,38 @@ void maman_ibaz_do_action (MamanIbaz *self); static void maman_ibaz_base_init (gpointer g_class) { - static gboolean initialized = FALSE; + static gboolean initialized = FALSE; - if (!initialized) { - /* create interface signals here. */ - initialized = TRUE; - } + if (!initialized) { + /* create interface signals here. */ + initialized = TRUE; + } } GType maman_ibaz_get_type (void) { - static GType type = 0; - if (type == 0) { - static const GTypeInfo info = { - sizeof (MamanIbazClass), - maman_ibaz_base_init, /* base_init */ - NULL, /* base_finalize */ - NULL, /* class_init */ - NULL, /* class_finalize */ - NULL, /* class_data */ - 0, - 0, /* n_preallocs */ - NULL /* instance_init */ - }; - type = g_type_register_static (G_TYPE_INTERFACE, "MamanIbaz", &info, 0); - } - return type; + static GType type = 0; + if (type == 0) { + static const GTypeInfo info = { + sizeof (MamanIbazClass), + maman_ibaz_base_init, /* base_init */ + NULL, /* base_finalize */ + NULL, /* class_init */ + NULL, /* class_finalize */ + NULL, /* class_data */ + 0, + 0, /* n_preallocs */ + NULL /* instance_init */ + }; + type = g_type_register_static (G_TYPE_INTERFACE, "MamanIbaz", &info, 0); + } + return type; } void maman_ibaz_do_action (MamanIbaz *self) { - MAMAN_IBAZ_GET_CLASS (self)->do_action (self); + MAMAN_IBAZ_GET_CLASS (self)->do_action (self); } @@ -799,12 +829,12 @@ typedef struct _MamanBaz MamanBaz; typedef struct _MamanBazClass MamanBazClass; struct _MamanBaz { - GObject parent; - int instance_member; + GObject parent; + int instance_member; }; struct _MamanBazClass { - GObjectClass parent; + GObjectClass parent; }; GType maman_baz_get_type (void); @@ -822,32 +852,32 @@ GType maman_baz_get_type (void); GType maman_baz_get_type (void) { - static GType type = 0; - if (type == 0) { - static 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 */ - baz_instance_init /* instance_init */ - }; - static 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; + static GType type = 0; + if (type == 0) { + static 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 */ + baz_instance_init /* instance_init */ + }; + static 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; } This function is very much like all the similar functions we looked at previously. The only interface-specific @@ -861,21 +891,21 @@ maman_baz_get_type (void) static void baz_do_action (MamanBaz *self) { - g_print ("Baz implementation of IBaz interface Action: 0x%x.\n", self->instance_member); + g_print ("Baz implementation of IBaz interface Action: 0x%x.\n", self->instance_member); } static void -baz_interface_init (gpointer g_iface, - gpointer iface_data) +baz_interface_init (gpointer g_iface, + gpointer iface_data) { - MamanIbazClass *klass = (MamanIbazClass *)g_iface; - klass->do_action = (void (*) (MamanIbaz *self))baz_do_action; + MamanIbazClass *klass = (MamanIbazClass *)g_iface; + klass->do_action = (void (*) (MamanIbaz *self))baz_do_action; } static void baz_instance_init (GTypeInstance *instance, gpointer g_class) { - MamanBaz *self = (MamanBaz *)instance; - self->instance_member = 0xdeadbeaf; + MamanBaz *self = (MamanBaz *)instance; + self->instance_member = 0xdeadbeaf; } baz_interface_init merely initializes the interface methods to the implementations @@ -900,38 +930,38 @@ baz_instance_init (GTypeInstance *instance, interface I2. The example below shows the GObject equivalent: - type = g_type_register_static (G_TYPE_INTERFACE, "MamanIbar", &info, 0); - /* Make the MamanIbar interface require MamanIbaz interface. */ - g_type_interface_add_prerequisite (type, MAMAN_TYPE_IBAZ); + type = g_type_register_static (G_TYPE_INTERFACE, "MamanIbar", &info, 0); + /* Make the MamanIbar interface require MamanIbaz interface. */ + g_type_interface_add_prerequisite (type, MAMAN_TYPE_IBAZ); The code shown above adds the MamanIbaz interface to the list of prerequisites of MamanIbar while the code below shows how an implementation can implement both interfaces and register their implementations: static void ibar_do_another_action (MamanBar *self) { - g_print ("Bar implementation of IBar interface Another Action: 0x%x.\n", self->instance_member); + g_print ("Bar implementation of IBar interface Another Action: 0x%x.\n", self->instance_member); } static void -ibar_interface_init (gpointer g_iface, - gpointer iface_data) +ibar_interface_init (gpointer g_iface, + gpointer iface_data) { - MamanIbarClass *klass = (MamanIbarClass *)g_iface; - klass->do_another_action = (void (*) (MamanIbar *self))ibar_do_another_action; + MamanIbarClass *klass = (MamanIbarClass *)g_iface; + klass->do_another_action = (void (*) (MamanIbar *self))ibar_do_another_action; } static void ibaz_do_action (MamanBar *self) { - g_print ("Bar implementation of IBaz interface Action: 0x%x.\n", self->instance_member); + g_print ("Bar implementation of IBaz interface Action: 0x%x.\n", self->instance_member); } static void -ibaz_interface_init (gpointer g_iface, - gpointer iface_data) +ibaz_interface_init (gpointer g_iface, + gpointer iface_data) { - MamanIbazClass *klass = (MamanIbazClass *)g_iface; - klass->do_action = (void (*) (MamanIbaz *self))ibaz_do_action; + MamanIbazClass *klass = (MamanIbazClass *)g_iface; + klass->do_action = (void (*) (MamanIbaz *self))ibaz_do_action; } @@ -939,48 +969,48 @@ static void bar_instance_init (GTypeInstance *instance, gpointer g_class) { - MamanBar *self = (MamanBar *)instance; - self->instance_member = 0x666; + MamanBar *self = (MamanBar *)instance; + self->instance_member = 0x666; } GType maman_bar_get_type (void) { - static GType type = 0; - if (type == 0) { - static const GTypeInfo info = { - sizeof (MamanBarClass), - NULL, /* base_init */ - NULL, /* base_finalize */ - NULL, /* class_init */ - NULL, /* class_finalize */ - NULL, /* class_data */ - sizeof (MamanBar), - 0, /* n_preallocs */ - bar_instance_init /* instance_init */ - }; - static const GInterfaceInfo ibar_info = { - (GInterfaceInitFunc) ibar_interface_init, /* interface_init */ - NULL, /* interface_finalize */ - NULL /* interface_data */ - }; - static const GInterfaceInfo ibaz_info = { - (GInterfaceInitFunc) ibaz_interface_init, /* interface_init */ - NULL, /* interface_finalize */ - NULL /* interface_data */ - }; - type = g_type_register_static (G_TYPE_OBJECT, - "MamanBarType", - &info, 0); - g_type_add_interface_static (type, - MAMAN_TYPE_IBAZ, - &ibaz_info); - g_type_add_interface_static (type, - MAMAN_TYPE_IBAR, - &ibar_info); - } - return type; + static GType type = 0; + if (type == 0) { + static const GTypeInfo info = { + sizeof (MamanBarClass), + NULL, /* base_init */ + NULL, /* base_finalize */ + NULL, /* class_init */ + NULL, /* class_finalize */ + NULL, /* class_data */ + sizeof (MamanBar), + 0, /* n_preallocs */ + bar_instance_init /* instance_init */ + }; + static const GInterfaceInfo ibar_info = { + (GInterfaceInitFunc) ibar_interface_init, /* interface_init */ + NULL, /* interface_finalize */ + NULL /* interface_data */ + }; + static const GInterfaceInfo ibaz_info = { + (GInterfaceInitFunc) ibaz_interface_init, /* interface_init */ + NULL, /* interface_finalize */ + NULL /* interface_data */ + }; + type = g_type_register_static (G_TYPE_OBJECT, + "MamanBarType", + &info, 0); + g_type_add_interface_static (type, + MAMAN_TYPE_IBAZ, + &ibaz_info); + g_type_add_interface_static (type, + MAMAN_TYPE_IBAR, + &ibar_info); + } + return type; } It is very important to notice that the order in which interface implementations are added to the main object @@ -1013,8 +1043,8 @@ maman_bar_get_type (void) - 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) + 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. @@ -1034,40 +1064,40 @@ uses this method. The code below shows how the user can connect a callback to th for this simple example is located in sample/signal/maman-file.{h|c} and in sample/signal/test.c - file = g_object_new (MAMAN_FILE_TYPE, NULL); +file = g_object_new (MAMAN_FILE_TYPE, NULL); - g_signal_connect (G_OBJECT (file), "write", - (GCallback)write_event, - NULL); +g_signal_connect (G_OBJECT (file), "write", + (GCallback)write_event, + NULL); - maman_file_write (file, buffer, 50); +maman_file_write (file, buffer, 50); The MamanFile signal is registered in the class_init function: - klass->write_signal_id = - g_signal_newv ("write", - G_TYPE_FROM_CLASS (g_class), - G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS, - NULL /* class closure */, - NULL /* accumulator */, - NULL /* accu_data */, - g_cclosure_marshal_VOID__VOID, - G_TYPE_NONE /* return_type */, - 0 /* n_params */, - NULL /* param_types */); +klass->write_signal_id = + g_signal_newv ("write", + G_TYPE_FROM_CLASS (g_class), + G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS, + NULL /* class closure */, + NULL /* accumulator */, + NULL /* accu_data */, + g_cclosure_marshal_VOID__VOID, + G_TYPE_NONE /* return_type */, + 0 /* n_params */, + NULL /* param_types */); and the signal is emited in maman_file_write: void maman_file_write (MamanFile *self, guint8 *buffer, guint32 size) { - /* First write data. */ - /* Then, notify user of data written. */ - g_signal_emit (self, MAMAN_FILE_GET_CLASS (self)->write_signal_id, - 0 /* details */, - NULL); + /* First write data. */ + /* Then, notify user of data written. */ + g_signal_emit (self, MAMAN_FILE_GET_CLASS (self)->write_signal_id, + 0 /* details */, + NULL); } As shown above, you can safely set the details parameter to zero if you do not know what it can be used for. @@ -1110,26 +1140,26 @@ and use the Makefile provided in sample/signal/Makefile to of the object MamanFileComplex (full source for this object is included in sample/signal/maman-file-complex.{h|c}): - GClosure *default_closure; - GType param_types[2]; - - default_closure = g_cclosure_new (G_CALLBACK (default_write_signal_handler), - (gpointer)0xdeadbeaf /* user_data */, - NULL /* destroy_data */); - - param_types[0] = G_TYPE_POINTER; - param_types[1] = G_TYPE_UINT; - klass->write_signal_id = - g_signal_newv ("write", - G_TYPE_FROM_CLASS (g_class), - G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS, - default_closure /* class closure */, - NULL /* accumulator */, - NULL /* accu_data */, - maman_file_complex_VOID__POINTER_UINT, - G_TYPE_NONE /* return_type */, - 2 /* n_params */, - param_types /* param_types */); +GClosure *default_closure; +GType param_types[2]; + +default_closure = g_cclosure_new (G_CALLBACK (default_write_signal_handler), + (gpointer)0xdeadbeaf /* user_data */, + NULL /* destroy_data */); + +param_types[0] = G_TYPE_POINTER; +param_types[1] = G_TYPE_UINT; +klass->write_signal_id = + g_signal_newv ("write", + G_TYPE_FROM_CLASS (g_class), + G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS, + default_closure /* class closure */, + NULL /* accumulator */, + NULL /* accu_data */, + maman_file_complex_VOID__POINTER_UINT, + G_TYPE_NONE /* return_type */, + 2 /* n_params */, + param_types /* param_types */); The code shown above first creates the closure which contains the code to complete the file write. This closure is registered as the default class_closure of the newly created signal. @@ -1142,9 +1172,9 @@ a skeleton: static void default_write_signal_handler (GObject *obj, guint8 *buffer, guint size, gpointer user_data) { - g_assert (user_data == (gpointer)0xdeadbeaf); - /* Here, we trigger the real file write. */ - g_print ("default signal handler: 0x%x %u\n", buffer, size); + g_assert (user_data == (gpointer)0xdeadbeaf); + /* Here, we trigger the real file write. */ + g_print ("default signal handler: 0x%x %u\n", buffer, size); } @@ -1154,11 +1184,11 @@ triggers the signal emission: void maman_file_complex_write (MamanFileComplex *self, guint8 *buffer, guint size) { - /* trigger event */ - g_signal_emit (self, - MAMAN_FILE_COMPLEX_GET_CLASS (self)->write_signal_id, - 0, /* details */ - buffer, size); + /* trigger event */ + g_signal_emit (self, + MAMAN_FILE_COMPLEX_GET_CLASS (self)->write_signal_id, + 0, /* details */ + buffer, size); } @@ -1178,34 +1208,34 @@ you are not reading this). static void complex_write_event_before (GObject *file, guint8 *buffer, guint size, gpointer user_data) { - g_assert (user_data == NULL); - g_print ("Complex Write event before: 0x%x, %u\n", buffer, size); + g_assert (user_data == NULL); + g_print ("Complex Write event before: 0x%x, %u\n", buffer, size); } static void complex_write_event_after (GObject *file, guint8 *buffer, guint size, gpointer user_data) { - g_assert (user_data == NULL); - g_print ("Complex Write event after: 0x%x, %u\n", buffer, size); + g_assert (user_data == NULL); + g_print ("Complex Write event after: 0x%x, %u\n", buffer, size); } static void test_file_complex (void) { - guint8 buffer[100]; - GObject *file; + guint8 buffer[100]; + GObject *file; - file = g_object_new (MAMAN_FILE_COMPLEX_TYPE, NULL); + file = g_object_new (MAMAN_FILE_COMPLEX_TYPE, NULL); - g_signal_connect (G_OBJECT (file), "write", - (GCallback)complex_write_event_before, - NULL); + g_signal_connect (G_OBJECT (file), "write", + (GCallback)complex_write_event_before, + NULL); - g_signal_connect_after (G_OBJECT (file), "write", - (GCallback)complex_write_event_after, - NULL); + g_signal_connect_after (G_OBJECT (file), "write", + (GCallback)complex_write_event_after, + NULL); - maman_file_complex_write (MAMAN_FILE_COMPLEX (file), buffer, 50); + maman_file_complex_write (MAMAN_FILE_COMPLEX (file), buffer, 50); - g_object_unref (G_OBJECT (file)); + g_object_unref (G_OBJECT (file)); } The code above generates the following output on my machine: @@ -1255,12 +1285,12 @@ Complex Write event after: 0xbfffe280, 50 the write function pointer. struct _MamanFileSimpleClass { - GObjectClass parent; + GObjectClass parent; - guint write_signal_id; + guint write_signal_id; - /* signal default handlers */ - void (*write) (MamanFileSimple *self, guint8 *buffer, guint size); + /* signal default handlers */ + void (*write) (MamanFileSimple *self, guint8 *buffer, guint size); }; The write function pointer is initialied in the class_init function of the object @@ -1270,25 +1300,25 @@ static void maman_file_simple_class_init (gpointer g_class, gpointer g_class_data) { - GObjectClass *gobject_class = G_OBJECT_CLASS (g_class); - MamanFileSimpleClass *klass = MAMAN_FILE_SIMPLE_CLASS (g_class); + GObjectClass *gobject_class = G_OBJECT_CLASS (g_class); + MamanFileSimpleClass *klass = MAMAN_FILE_SIMPLE_CLASS (g_class); - klass->write = default_write_signal_handler; + klass->write = default_write_signal_handler; Finally, the signal is created with g_signal_new in the same class_init function: - klass->write_signal_id = - g_signal_new ("write", - G_TYPE_FROM_CLASS (g_class), - G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS, - G_STRUCT_OFFSET (MamanFileSimpleClass, write), - NULL /* accumulator */, - NULL /* accu_data */, - maman_file_complex_VOID__POINTER_UINT, - G_TYPE_NONE /* return_type */, - 2 /* n_params */, - G_TYPE_POINTER, - G_TYPE_UINT); +klass->write_signal_id = + g_signal_new ("write", + G_TYPE_FROM_CLASS (g_class), + G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS, + G_STRUCT_OFFSET (MamanFileSimpleClass, write), + NULL /* accumulator */, + NULL /* accu_data */, + maman_file_complex_VOID__POINTER_UINT, + G_TYPE_NONE /* return_type */, + 2 /* n_params */, + G_TYPE_POINTER, + G_TYPE_UINT); Of note, here, is the 4th argument to the function: it is an integer calculated by the G_STRUCT_OFFSET macro which indicates the offset of the member write from the start of the @@ -1370,8 +1400,8 @@ maman_file_simple_class_init (gpointer g_class,