GLib is an underlying library that provides many useful definitions and functions when creating GDK and GTK applications.
Includes definitions of basic types and restrictions, standard macros, type conversions, byte orders, storage allocations, warnings and assertions, message logging, timers, string tools, hook functions, syntactic scanners, dynamic load modules, and string automatic completion, as well as a number of data types and related operations.
Includes storage block, bidirectional linked list, one-way linked list, hash table, dynamic list, relationship and tuple, and caching. Finally, glib has a good portability, so using glib as the support of the underlying application, it also guarantees the portability of the application.
Type definition:
1. Integer types: gint8, Guint8, Gint16, Guint16, Gint32, Guint32, Gint64, Guint64. Not all platforms offer 64-bit integral type
2. Integer type Gshort, Glong, Gint and short, long, int the same
3. Boolean type Gboolean:gboolean can take two values: True and False
4. Character type Gchar and char same
5. Floating-point gfloat and gdouble are completely equivalent to float and double
6. The pointer gpointer corresponds to the void* of standard C
7. Gconstpointer for the const void* of standard C
GLib Macros:
Conversion between integer and pointer type
1. Gint_to_pointer (a): conversion of int to Gpointer type
2. Gpointer_to_int (a): Convert gpointer type to INT type
3. Guint_to_pointer (a): convert UINT type to Gpointer type
4. Gpointer_to_uint (a): Convert Gpointer type to integral type
5. NULL macro definition: #define NULL (void*) 0 (that is, 0 is an integer data, and Null is the pointer type)
One, two-way linked list
Each element in a doubly linked list contains a piece of data and a pointer to the front and back elements. This makes the two-way movement of the linked list easier.
The stored data type is gpointer, and in glib, a pointer to the actual data is gpointer.
There is no function to create a linked list, but simply to create a glist* variable and set it to null.
GLib functions provided in a two-way linked list:
Glist *g_list_append (glist *list, gpointer data): Add a new element to the end of the list glist *g_list_prepend
(glist *list, gpointer data) : Adds a new element to the list header
glist *g_list_insert (glist *list, gpointer data, gint position): Inserts a new element into the list at the specified location
glist Remove (glist *list, gpointer data): Removes an element with a value of data from the list, and if the element does not exist, the list does not change
glist *g_list_free (glist *list) : Number frees all storage areas used by Glist
glist *g_list_remove_link (glist *list, glist *link)
glist *g_list_reverse (glist *list) : list element position inversion
glist *g_list_nth (glist *list, Gint N): Gets the specified location element
glist *g_list_find (glist *list, gpointer data) : Finds an element with the specified value in the list, no returns null
glist *g_list_last (glist *list): Gets the last element in the list glist *g_list_first
(glist *list) : Gets the first element in the list
gint g_list_length (glist *list): Returns the number of list elements
void G_list_foreach (Glist *list, Gfunc func, Gpointer Data): Traversal list
gint g_list_index (glist *list, gconstpointer data): Returns the position of the specified element in the list, no matching element is found, return 1. The element position is calculated starting at 0.
#include <stdio.h> #include <stdlib.h> #include <glib.h> #include <string.h> typedef struct _TEA
Cher {gint age;
Gchar *name;
}teacher;
void Each_callback (gpointer data, Gpointer user_data) {Teacher *t = (Teacher *) data;
G_print ("T->name =%s, user param:%s\n", T->name, (char *) user_data);
int main (int argc,char *argv[]) {glist *list = NULL;
Teacher *pteacher1 = g_new0 (teacher,1);
Pteacher1->name = G_new0 (char,128);
strcpy (Pteacher1->name, "Tiny Jason");
List = G_list_append (list, pTeacher1);
Teacher *pteacher2 = g_new0 (teacher,1);
Pteacher2->name = G_new0 (char,128);
strcpy (Pteacher2->name, "Rorash");
List = G_list_prepend (list, pTeacher2);
Teacher *pteacher3 = g_new0 (teacher,1);
Pteacher3->name = G_new0 (char,128);
strcpy (Pteacher3->name, "Alibaba");
List = G_list_prepend (list, pTeacher3);
G_list_foreach (list, each_callback, "User_data"); Glist *second = g_list_find (list, pTeacher2);
if (second!= NULL) {teacher* t = (teacher*) second->data;
G_print ("Name:%s\n", t->name);
List = G_list_remove (list, pTeacher2);
G_list_foreach (list, each_callback, "User_data");
Gint len = g_list_length (list);
G_print ("Len:%d\n", Len);
Glist *nnode = G_list_nth (list,1);
if (Nnode!= NULL) {teacher* t = (teacher*) nnode->data;
G_print ("Name:%s\n", t->name);
} g_list_free (list);
return 0;
}
Makefile
. suffixes:.c. o
cc=gcc
srcs=test_glib.c
objs=$ (SRCS:.C=.O)
exec=test_glib all:$
(OBJS)
$ ( CC)-O $ (EXEC) $ (OBJS) ' Pkg-config--libs glib-2.0 '
. C.O:
$ (cc)-o $@-c-g $< ' pkg-config--cflags ' glib-2.0 '
clean:
rm-f $ (OBJS)
Run Result:
T->name = Alibaba, user param:user_data
t->name = rorash, user param:user_data
t->name = Tiny Jason, US Er param:user_data
name:rorash
t->name = Alibaba, user param:user_data
t->name = Tiny Jason, user p Aram:user_data
len:2
name:tiny Jason
two, one-way linked list
[CPP]View Plain copy gslist *g_slist_append (gslist *list, gpointer data): List finally adds an element gslist *g_slist_prepend (gslist *list, GPO Inter data): the first new element in the list is Gslist *g_slist_insert (gslist *list, gpointer data, gint position): Specify the location of the list to insert a new element gslist *g_slist _remove (gslist *list, gpointer data): Delete elements with value data gslist *g_slist_reverse (gslist *list) in the list: Reverse element position Gslist *g_slist_nth ( Gslist *list, Gint N): Returns the next element in the list gslist *g_slist_find (gslist *list, gpointer data): Finds the element with the specified data, and returns null Gslist *G_SLI St_last (gslist *list): Find the last element of a list Gint g_slist_length (gslist *list): Returns the number of list elements void G_slist_foreach (Gslist *list, Gfunc Func, Gpointer data): Traversing the list
third, storage management
[CPP]View Plain copy gpointer g_malloc (gulong size): This is an alternate function for malloc and does not need to check the return value. If the storage allocation fails for any reason, the application terminates. Gpointer g_malloc0 (gulong size): Has the same functionality as G_malloc, but before returning a pointer to an allocation storage block, clear the storage block by 0. Gpointer G_realloc (gpointer mem, Gulong size): Reassign the pointer starting with the MEM and set the size byte. void G_free (Gpointer mem): Frees allocated storage blocks. If the MEM is null, it is returned directly.
Four, Timer
A timer function can be used to record an action, or to record a program's intermittent elapsed time.
[CPP]View Plain copy Gtimer *g_timer_new (void): Create a new timer void G_timer_destroy (Gtimer *timer): Unregister timer void G_timer_start (Gtimer *timer): Timer started void G_timer_stop (Gtimer *timer): Stop timed void G_timer_reset (Gtimer *timer): Reset timer void G_timer_continue (g Timer *timer): Continue to Time Gdobule g_timer_elapsed (Gtimer *timer, Gulong *microseconds): Decide what time consuming
Example:[CPP] View plain copy gtimer *timer; void each_callback (gpointer data, Gpointer user_data) { g_print ("element:%s, user Param:%s\n ", (gchar*) data, (gchar*) user_data); } Int main ( int argc, char *argv[] ) { GList *list = NULL; gulong seconds; int i=0; timer = g_timer_new (); list = g_list_append (list, "second"); list = g_list_prepend (list, "a"); g_timer_start ( Timer); g_list_foreach (list, each_callback, "User_data"); g_tImer_stop (timer); g_timer_elapsed (timer, &seconds); g_print ("use seconds:%ld\n", seconds); g_ Timer_continue (timer); for (i; i<=1000; i++) { g_print ("%d", i); } g_timer_elapsed (timer, &seconds); g_print ("Use seconds: %ld\n ", seconds); return 0; }
Five, string processing
In programming, it is often necessary to splice, intercept, and capitalization the string, which is very tedious in C. Now glib defines a new type called gstring, which can grow automatically and provides
A series of convenient operation functions.
struct gstring{
Gchar *str;/* point to the current string ending with a/*
Gint len;/* Current Character length * *
}
[CPP] View Plain copy gstring *g_string_new (gchar *init): Create Glist type gstring *g_string_truncate (Gstring *string, gint len): intercepts a specified length of string gstring *g_string_append (gstring * String, gchar *val): Append string gstring *g_string_append_c at end (gstring *string, GCHAR&NBSP;C): End with a single character gstring *g_string_prepend (Gstring *string, gchar *val) : Start Insert String Gstring *g_string_prepend_c (gstring *string, gchar c): Start by inserting a single character void g_string_sprintf (gstring *string, gchar *fmt, .) : Format string gchar *g_strdup (const gchar *str): Copy string, return a newly assigned string. gchar *g_strndup (const gchar *str, gsize n): Copies the specified number of strings, returns the newly allocated string Gchar *g_strstr_len (const gchar *haystack, gssize haystack_len, const gchar *needle): A pointer to the specified character appears for the first time within a defined length &NBSP;&NBSp Gchar *g_strrstr (Const gchar *haystrack, const gchar *needle): Searches for the last occurrence of a string in the haystack. Gchar *g_strrstr_len (const gchar *haystrack, gssize haystrack_len, Const gchar *needle) Gboolean g_str_hash_prefix (const gchar *str, Const gchar *prefix): Returns whether the string starts with a prefix int g_strcmp0 (const char *str1, CONST&NBSP;CHAR&NBSP;*STR2): Compare two strings Gchar **g_strsplit (const gchar *string, Const gchar *delimiter, gint max_tokens): Split string, save array gchar *g_strconcat ( const gchar *string1, ...) : String Stitching gchar *g_strjoin (const gchar *separator, ) : Isolate and splice with a string
More Http://gtk-doc-cn.googlecode.com/svn/docs/glib/glib-String-Utility-Functions.html#g-strdup
Six, error handling
[CPP] view plain copy gchar *g_strdup (const Gchar *STR): Overrides the StrDup function. Copies the contents of the original string into the newly allocated storage block, returning a pointer to it. Gchar *g_strerror (Gint errnum); void G_error (Gchar *format, ...); Error message: "* * ERROR * *" and exit the program. Used only on fatal errors. void G_warning (Gchar *format, ...) : Error Tip: "* * WARNING * *" void G_message (Gchar *format, ...) : print "message" Void G_print (Gchar *format, ...) before passing the string. : Alternate printf function
In addition to the above, glib also provides a number of features, including code conversion, regular, XMP parsing, test framework, and so on.
GLib about Thread,mutex,cond
#include <glib.h> #include <stdio.h> static int num = 0;
Gmutex Mutex;
Gcond cond;
Gboolean _thread_main1 (void *data) {while (1) {g_mutex_lock (&mutex);
while (num <= 0) {g_printf ("consumer[%d] is wating.....\n", (int) data);
G_cond_wait (&cond, &mutex);
g_printf ("consumer[%d] Wake up.....\n", (int) data);
} g_printf ("consmuer[%d] Before,num =%d.....\n", (int) data,num);
num--;
g_printf ("consmuer[%d] After,num =%d.....\n", (int) data,num);
G_mutex_unlock (&mutex);
Sleep (1);
return TRUE;
} Gboolean _thread_main2 (void *data) {while (1) {g_mutex_lock (&mutex);
num++;
if (num > 0) {g_printf ("Prepare to sigal...please wait for 5 seconds\n");
Sleep (5);
G_cond_signal (&cond);
g_printf ("after g_cond_signal\n"); } g_mutex_unlock (; a mutex);
Sleep (2);
return TRUE;
int main (int argc,char *argv[]) {Gthread *consumer1 = NULL;
Gthread *consumer2 = NULL;
Gthread *consumer3 = NULL;
Gthread *thread2 = NULL;
G_mutex_init (&mutex);
G_cond_init (&cond);
Consumer1 = G_thread_new ("Consumer1", (Gthreadfunc) _thread_main1, (void*) 1);
Consumer2 = G_thread_new ("Consumer2", (Gthreadfunc) _thread_main1, (void*) 2);
Consumer3 = G_thread_new ("Consumer3", (Gthreadfunc) _thread_main1, (void*) 3);
Thread2 = G_thread_new ("Thread2", (Gthreadfunc) _thread_main2, NULL);
G_thread_join (Consumer1);
G_thread_join (CONSUMER2);
G_thread_join (CONSUMER3);
G_thread_join (THREAD2);
return 0;
}
Results:
CONSUMER[1] is wating .....
CONSUMER[2] is wating .....
Prepare to Sigal...please wait for 5 seconds
After g_cond_signal
CONSUMER[1] Wake up .....
CONSMUER[1] Before,num = 1 .....
CONSMUER[1] After,num = 0 .....
CONSUMER[3] is wating .....
CONSUMER[1] is wating .....
Prepare to Sigal...please wait for 5 seconds
After g_cond_signal
CONSUMER[2] Wake up .....
CONSMUER[2] Before,num = 1 .....
CONSMUER[2] After,num = 0 .....
CONSUMER[2] is wating .....
Prepare to Sigal...please wait for 5 seconds
After g_cond_signal
CONSUMER[3] Wake up .....
CONSMUER[3] Before,num = 1 .....
CONSMUER[3] After,num = 0 .....
CONSUMER[3] is wating .....
Prepare to Sigal...please wait for 5 seconds
After g_cond_signal
CONSUMER[1] Wake up .....
CONSMUER[1] Before,num = 1 .....
CONSMUER[1] After,num = 0 .....
CONSUMER[1] is wating .....
Prepare to Sigal...please wait for 5 seconds
After g_cond_signal
CONSUMER[2] Wake up .....
CONSMUER[2] Before,num = 1 .....
CONSMUER[2] After,num = 0 .....
CONSUMER[2] is wating .....