Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

Gtk+/Gnome Application Development
Prev Home Next

Frequently Used Macros

glib defines a number of familiar macros used in many C programs, shown in Figure 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 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 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.

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 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. Macros for storing integers in pointers

Gtk+/Gnome Application Development
Prev Home Next

 
 
  Published under free license. Design by Interspire