[Previous] [Contents] [Next]

21. GLib

GLib is a lower-level library that provides many useful definitions and functions available for use when creating GDK and GTK applications. These include definitions for basic types and their limits, standard macros, type conversions, byte order, memory allocation, warnings and assertions, message logging, timers, string utilities, hook functions, a lexical scanner, dynamic loading of modules, and automatic string completion. A number of data structures (and their related operations) are also defined, including memory chunks, doubly-linked lists, singly-linked lists, hash tables, strings (which can grow dynamically), string chunks (groups of strings), arrays (which can grow in size as elements are added), balanced binary trees, N-ary trees, quarks (a two-way association of a string and a unique integer identifier), keyed data lists (lists of data elements accessible by a string or integer id), relations and tuples (tables of data which can be indexed on any number of fields), and caches.

A summary of some of GLib's capabilities follows; not every function, data structure, or operation is covered here. For more complete information about the GLib routines, see the GLib documentation. One source of GLib documentation is http://www.gtk.org/.

21.1 Definitions

Definitions for the extremes of many of the standard types are:


The following table shows how glib's types relate to Pascal types. The ones left unspecified are dynamically set depending on the architecture. Remember to avoid counting on the size of a pointer if you want to be portable! E.g., a pointer on an Alpha is 8 bytes, but 4 on Intel 80x86 family CPUs.

 gchar           char
 gshort          system.integer
 glong           longint
 gint            longint
 gboolean        longbool
 gchar           uchar
 gushort         word
 gulong          cardinal
 guint           cardinal
 gfloat          float
 gdouble         double
 gsize           cardinal
 gssize          longint
 gpointer        pointer
 gconstpointer   pointer
 gint8           shortint
 guint8          byte
 gint16          system.integer
 gint32          longint
 guint32         cardinal

21.2 Doubly Linked Lists

The following functions are used to create, manage, and destroy standard doubly linked lists. Each element in the list contains a piece of data, together with pointers which link to the previous and next elements in the list. This enables easy movement in either direction through the list. The data item is of type gpointer, which means the data can be a pointer to your real data or (through casting) a numeric value (but do not assume that integer and gpointer have the same size!). These routines internally allocate list elements in blocks, which is more efficient than allocating elements individually.

There is no function to specifically create a list. Instead, simply create a variable of type PGList and set its value to nil. nil is considered to be the empty list.

To add elements to a list, use the g_list_append(), g_list_prepend(), g_list_insert(), or g_list_insert_sorted() routines. In all cases they accept a pointer to the beginning of the list, and return the (possibly changed) pointer to the beginning of the list. Thus, for all of the operations that add or remove elements, be sure to save the returned value!

function g_list_append (list : PGList; data : gpointer) : PGList;

This adds a new element (with value data) onto the end of the list.

function g_list_prepend (list : PGList; data : gpointer) : PGList;

This adds a new element (with value data) to the beginning of the list.

function g_list_insert (list : PGList;
                        data : gpointer;
                        position : gint) : PGList;

This inserts a new element (with value data) into the list at the given position. If position is 0, this is just like g_list_prepend(); if position is less than 0, this is just like g_list_append().

function g_list_remove (list : PGList; data : gpointer) : PGList;

This removes the element in the list with the value data; if the element isn't there, the list is unchanged.

PROCEDURE g_list_free (list : PGList);

This frees all of the memory used by a GList. If the list elements refer to dynamically-allocated memory, then they should be freed first.

There are many other GLib functions that support doubly linked lists; see the glib documentation for more information. Here are a few of the more useful functions' signatures:

function g_list_remove_link (list : PGList; link : PGList) : PGList;

function g_list_reverse (list : PGList) : PGList;

function g_list_nth (list : PGList; n : guint) : PGList;

function g_list_find (list : PGList; data : gpointer) : PGList;

function g_list_last (list : PGList) : PGList;

function g_list_first (list : PGList) : PGList;

function g_list_length (list : PGList) : guint;

PROCEDURE g_list_foreach (list : PGList;
                          func : TGFunc;
                          user_data : gpointer);

21.3 Singly Linked Lists

Many of the functions for singly linked lists are identical to the above. Here is a list of some of their operations:

function g_slist_append (list : PGSList;
                         data : gpointer) : PGSList;

function g_slist_prepend (list : PGSList;
                          data : gpointer) : PGSList;

function g_slist_insert (list : PGSList;
                         data : gpointer;
                         position : gint) : PGSList;

function g_slist_remove (list : PGSList;
                         data : gpointer) : PGSList;

function g_slist_remove_link (list : PGSList;
                              link : PGSList) : PGSList;

function g_slist_reverse (list : PGSList) : PGSList;

function g_slist_nth (list : PGSList;
                      n : guint) : PGSList;

function g_slist_find (list : PGSList;
                       data : gpointer) : PGSList;

function g_slist_last (list : PGSList) : PGSList;

function g_slist_length (list : PGSList) : guint;

procedure g_slist_foreach (list : PGSList;
                           func : tGFunc;
                           user_data : gpointer);

21.4 Memory Management

function g_malloc (size : gulong) : gpointer;

This is a replacement for the C language malloc(). You do not need to check the return value as it is done for you in this function. If the memory allocation fails for whatever reasons, your applications will be terminated. Not needed in Pascal.

function g_malloc0 (size : gulong) : gpointer;

Same as above, but zeroes the memory before returning a pointer to it.

function g_realloc (mem : gpointer;
                    size : gulong) : gpointer;

Relocates size bytes of memory starting at mem. Obviously, the memory should have been previously allocated.

procedure g_free (mem : gpointer);

Frees memory. Easy one. If mem is nil it simply returns.

procedure g_mem_profile();

Dumps a profile of used memory.

procedure g_mem_check (mem : gpointer);

Checks that a memory location is valid.

21.5 Timers

Timer functions can be used to time operations (e.g., to see how much time has elapsed). First, you create a new timer with g_timer_new(). You can then use g_timer_start() to start timing an operation, g_timer_stop() to stop timing an operation, and g_timer_elapsed() to determine the elapsed time.

function g_timer_new () : PGTimer;

procedure g_timer_destroy (timer : PGTimer);

procedure g_timer_start (timer : PGTimer);

procedure g_timer_stop (timer : PGTimer);

procedure g_timer_reset (timer : PGTimer);

function g_timer_elapsed (timer : PGTimer; 
                          microseconds : pgulong) : gdouble;

21.6 String Handling

GLib defines a new type called a GString, which is similar to a standard C string but one that grows automatically. Its string data is null-terminated. What this gives you is protection from buffer overflow programming errors within your program. This is a very important feature, and hence I recommend that you make use of GStrings. GString itself has a simple public definition:

   PGString = ^TGString;
   TGString = record
                 str : pgchar;
                 { Points to the string's NIL terminated value }
                 len : gint;
                 { Current length }

As you might expect, there are a number of operations you can do with a GString.

function g_string_new (init : pgchar) : PGString;

This constructs a GString, copying the string value of init into the GString and returning a pointer to it. nil may be given as the argument for an initially empty GString.

procedure g_string_free (thestring : PGString;
                         free_segment : gboolean);

This frees the memory for the given GString. If free_segment is true, then this also frees its character data.

function g_string_assign (lval :  PGString;
                          rval : pgchar) : PGString;

This copies the characters from rval into lval, destroying the previous contents of lval. Note that lval will be lengthened as necessary to hold the string's contents.

The rest of these functions should be relatively obvious (the _c versions accept a character instead of a string):

function g_string_truncate (_string : PGString;
                            len : gint) : PGString;

function g_string_append (_string : PGString;
                          val : pgchar) : PGString;

function g_string_append_c (_string : PGString;
                            c : gchar) : PGString;

function g_string_prepend (_string : PGString;
                           val : pgchar) : PGString;

function g_string_prepend_c (_string : PGString;
                             c : gchar) : PGString;

procedure g_string_sprintf (_string : PGString;
                            fmt : pgchar;
                            args : array of const);

procedure g_string_sprintfa (_string : PGString; 
                             fmt : pgchar;
                             args : array of const);

21.7 Utility and Error Functions

function g_strdup (thestring : pgchar) : pgchar;

Copies the original strings contents to newly allocated memory, and returns a pointer to it.

function g_strerror (errnum : gint) : pgchar;

This is recommended for use with all error messages. It's nice, and it's portable. The output is usually of the form:

program name:function that failed:file or further description:strerror

Here's an example of one such call which could be used in our hello_world program:

   g_print("hello_world:open:%s:%s\n", filename, g_strerror(errno));
procedure g_error (format : pgchar; array of const);

Prints an error message. The format is just like g_print, but it prepends "** ERROR **: " to your message, and exits the program. Use only for fatal errors.

procedure g_warning (format : pgchar; array of const);

Same as above, but prepends "** WARNING **: ", and does not exit the program.

procedure g_message (format : pgchar; array of const);

Prints "message: " prepended to the string you pass in.

procedure g_print (format : pgchar; array of const);

Replacement for printf() from C standard library.

And our last function:

function g_strsignal (signum : gint) : pgchar;

Prints out the name of the Unix system signal given the signal number. Useful in generic signal handling functions.

All of the above are more or less just stolen from glib.pp.

[Previous] [Contents] [Next]