Frequently Used Macros on Glib

glib defines a number of familiar macros used in many C programs, shown in Figure
2-1. All of these should be self-explanatory. MIN()/MAX() return the smaller or larger of their arguments. ABS() returns the absolute value of its argument. CLAMP(x, low, high) means x, unless x is outside the range [low, high]; if x is below the range, low is returned; if x is above the range, high is returned. In addition to the macros shown in Figure 2-1, TRUE/FALSE/NULL are defined as the usual 1/0/((void*)0).

#include <glib.h>

MAX( a ,	b ); MIN( a ,	b ); ABS( x );
CLAMP( x ,	low ,	high );

Figure 2-1. Familiar C Macros

There are also many macros unique to glib, such as the portable gpointer-to-gint and gpointer-to-guint conversions shown in Figure 2-2.

Most of glib’s data structures are designed to store a gpointer. If you want to store pointers to dynamically allocated objects, this is the right thing. However, sometimes you want to store a simple list of integers without having to dynamically allocate them. Though the C standard does not strictly guarantee it, it is possible to store a gint or guint in a gpointer variable on the wide range of platforms glib has been ported to; in some cases, an intermediate cast is required. The macros in Figure 2-2 abstract the presence of the cast.

Here’s an example:

gint my_int;
gpointer my_pointer;

my_int = 5;
my_pointer = GINT_TO_POINTER(my_int);
printf("We are storing %d\n", GPOINTER_TO_INT(my_pointer));

Be careful, though; these macros allow you to store an integer in a pointer, but storing a pointer in an integer will not work. To do that portably, you must store the pointer in a long. (It’s undoubtedly a bad idea to do so, however.)

#include <glib.h>

GINT_TO_POINTER(p); GPOINTER_TO_INT(p); GUINT_TO_POINTER(p); GPOINTER_TO_UINT(p);

Figure 2-2. Macros for storing integers in pointers

Source: GTK Gnome Application Development

3 thoughts on “Frequently Used Macros on Glib”

  1. well written article, i just bookmarked it for future reference. i would love to revisit on new articles. how can i set up the rss again? thanks!

    [WORDPRESS HASHCASH] The poster sent us ‘0 which is not a hashcash value.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: