OOP in C
On 2015/12/26 at 22:34
Despite C does not support OOP like C++ or Java, OOP concepts is still used in Android HAL module and GTK+ programs.
Inheretance
Simulating inheretance feature in C is done by simply putting the parent class as the first field in the structure. In this way, we can get all the parent fields in the child class and transform it to the parent type by using a simple pointer conversion.
typedef struct {
...
} Animal;
typedef struct {
Animal parent;
int dogAttribute1;
char dogAttribute2;
...
} Dog;
Dog *dog = new_dog();
Animal *animal = (Animal*) dog;
// access dog's inhereted field
Android HAL module
In Android, every HAL module must have hw_module_t
as the first field. For example, sensors_moudle_t.
GTK+
GTK+ programs use more OOP concepts for developing. The inheretance structure is this GObject <- GInitiallyUnowned <- GtkObject <- GtkWidget <- GtkContainer <- GtkBin <- GtkWindow
For most GTK functions, the first argument works as the this
pointer for OOP language.
GtkWidget* window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window), "title");
// this works like access gtk window member function
GTK_WINDOW
is a macro for type checking and casting
#define GTK_WINDOW(obj)
(G_TYPE_CHECK_INSTANCE_CAST((obj), GTK_TYPE_WINDOW, GtkWindow))