Analysis of Glib
content:
Fundamental Type Support Practical Function Data Type Reference About Authors
related information:
Container controls and layout tips in GTK 2.0 application GTK programming
In the Linux area:
Tutorial Tools & Product Codes and Component Project Articles
Song Guowei (gwsong52@sohu.com) Glib is the basic underlying core library of GTK and GNOME projects in May 2003, is a commonly used practical lightweight C library, which provides common data structures in C language. Definition, related processing functions, interesting and practical macros, portable packages, and some runtime, such as event cycles, threads, dynamic calls, object systems, etc. API. It can run on operating system platforms such as Linux, HP-UNIX, etc.), Windows, HP-UNIX, etc., such as Linux, HP-UNIX, etc.), Windows, OS2, and BEOS. Glib needs a support of the operating system that supports threads and a character integral conversion function iconv support, in fact, most modern operating systems have two features. GLIB consists of five parts: support, utility, data type, and object system. The latest version of GLIB is GLIB 2.2.1, you can download its source code from www.gtk.org. Use the application written in GLIB 2.0, add the `pkg-config -cflags -libs glib-2.0 in the compile command, such as compiling a program called Hello.c, and outputs an executable named hello The command is:
GCC `pkg-config -cflags -libs glib-2.0` Hello.c -o Hello
The three subsystems (GTHREAD), Plugins (Gmoudle) and Object Systems (G / I) are partially treated in GLIB, and should pay attention to the corresponding parameters when compiling. If the object system is used in the program, it should be added when compiling:
`pkg-config --cflags --Libs GOBJECT-2.0`
Use threads and compile:
`pkg-config --cflags --libs gthread-2.0`
Use the plugin to compile:
`pkg-config --cflags --libs gmoudle-2.0`
The basis of the basic type GLIB is composed of fundamentals, scope limiting macros, standard macros, type conversion macros, byte order transform macros, mathematical constant definitions, and miscellaneous macros. Here mainly introduces the basic type because they have large open source projects such as GTK , GNOME, MONO, such as GTK , GNOME, MONO. The basic type is also known as standard type, GLIB unifies the data type in the C language into its own data type, all starts with lowercase letters 'g', such as: gpointer is a pointer type (void *), Guint is unsigned integer ( Unsigned int), etc., there are some modifications such as GINT, GCHAR, etc., and int, char, etc. in C language is exactly the same. These data types are exactly the same as the data types in the C language. When you are familiar with it, you will find that their usage is more flexible, more intuitive is also more appreciable. Of course, you can use the data type in the C language directly, which does not affect the compilation of your written programs. In addition, the scope limit macro and type conversion macro are also more common, such as g_maxint represent the maximum INT value, convert the integer variable I to the pointer type with macro GINT_TO_POINTER (i), macro GPOINTER_TO_INT (P) convert the needle type variable P to integer . The value of the logical type Gboolean is defined in a constant macro, and further includes g_e representing a natural logarithm, g_pi represents a number of mathematical constants such as 1/2 of the circumferential rate. Support for core applications GLIB for core applications includes event loops, memory operations, thread operations, dynamic link libraries operations and errors and logs, etc. The following code demonstrates the simple application of the three functions of the event loop, memory operation, and thread: #include
Static Gmutex * Mutex = NULL;
Static gboolean t1_end = false;
Static gboolean t2_end = false;
Typedef struct _arg arg;
Struct_Arg
{
Gmainloop * loop;
Gint max;
}
Void Run_1 (Arg * Arg)
{
INT I;
For (i = 0; i
{
IF (g_mutex_trylock (mutex) == false)
{
// g_print ("% d: thread 2 locked the mutex / n", i);
g_print ("% D: thread 2 locks the mutual exclusive object / n", i);
g_mutex_unlock (mutex);
}
Else
{
g_usleep (10);
}
}
T1_END = True;
}
Void Run_2 (Arg * Arg)
{
INT I;
For (i = 0; i
{
IF (g_mutex_trylock (mutex) == false)
{
// g_print ("% D: Thread 1 Locked Mutex / N", i);
g_print ("% D: thread 1 locks mutually exclusive objects / n", i);
g_mutex_unlock (mutex);
}
Else
{
g_usleep (10);
}
}
T2_END = True;
}
Void Run_3 (arg * arg)
{
For (;;)
{
IF (T1_END && T2_END)
{
g_main_loop_quit (arg-> loop); Break;
}
}
}
Int main (int Argc, char * argv [])
{
Gmainloop * mloop;
Arg * arg;
IF (! g_thread_supported ())
g_thread_init (null);
mloop = g_main_loop_new (null, false);
Arg = g_new (arg, 1);
Arg-> loop = mloop;
Arg-> max = 11;
Mutex = g_mutex_new ();
g_thread_create (Run_1, Arg, True, NULL);
g_thread_create (Run_2, Arg, True, NULL);
g_thread_create (Run_3, Arg, True, NULL);
g_main_loop_run (mloop);
g_print ("Thread 3 Exit Event Cycle / N");
g_mutex_free (mutex);
g_print ("Release Mutex / N");
g_free (arg);
g_print ("memory / N" used by the release parameter);
}
The Makefile file is as follows:
CC = GCC
All:
$ (Cc) `pkg-config --cflags --libs glib-2.0 gthread-2.0` loop.c -o loop
The following is the output result: 0: Thread 1 Locked the mutually exclusive object 1: Thread 2 Locked the mutual exclusive object 2: Thread 1 Locked the mutually exclusive object 3: Thread 2 Locked the mutually exclusive object 4: Thread 1 Locked the mutually exclusive object 5: Thread 2 locks the mutually exclusive object 6: Thread 1 Locked the mutex 7: Thread 2 Locked the mutex 8: Thread 1 Locked the mutually exclusive object 9: Thread 2 Locked the mutually exclusive object 10: thread 1 lock The Mutual Exclusion Object Thread 3 Exits Event Cycle Release The memory-release parameter is used to release the above routine. The above routines created three threads, where RUN_1 and RUN_2 operate the mutual exclusive object, RUN_3 retrieves whether the first two threads end, such as end, then Perform g_main_loop_quit exit event loop. Since the running operation is uncertain, it is not necessarily that this output is. First, a structural type is defined to save the created event loop, the maximum number of cycles at the thread run, in general, if the data structure is allocated for this data structure, use arg * arg = (arg *) malloc (Sizeof Arg); Free (arg) when released; this traditional practice has made a headache in many C language, especially when it takes multiple operations, GLIB provides similar functions G_malloc and g_free, most It is the way to encapsulate the g_malloc function into macro g_new. This macro has two parameters. The first is the structural type, the second is the number of structures to allocate the structure, this code only uses an ARG data structure So g_new (arg, 1). Use g_free to be released at the end of the program. When thread initialization, first is the function g_thread_supported that determines whether the thread is initialized. If it returns false, it indicates that the thread is not initialized. At this time, you must initialize it with g_thread_init, which is a wise practice. The event loop GmainLoop is not immediately running, after running with g_main_loop_run, use g_main_loop_quit to exit, otherwise the loop will run, the parameters of these two functions are GmainLoop type pointers, not in the main function Run G_main_loop_quit directly, but put it in the thread function, this point needs to pay attention. Practical functions include nearly 20 utility, from simple characters to beginners to understand the XML parses, here is more simple: random number and timing. The following code demonstrates how to generate random integers between 1-100 and demonstrate how to calculate 30000,000 accumulated time when calculating: / * Until.c Used to test practical features * /
#include
Int main (int Argc, char * argv [])
{
Grand * rand;
Gtimer * Timer;
Gint n;
Gint i, j;
GINT X = 0;
Rand = g_rand_new (); // Create a random number object
FOR (n = 0; n <20; n )
{// produce random number and displayed
g_print ("% d / t", g_rand_int_range (rand, 1,100));
}
g_print ("/ n");
g_rand_free (rand); // Release the random number object
// Create a timer
Timer = g_timer_new ();
g_timer_start (time); // Start timing
For (i = 0; i <10000; i )
For (j = 0; j <3000; j ) x ; // Accumulated
g_timer_stop (time); / / End of time
// Output Timing Results
g_print ("% ld / tall:%. 2f seconds WAS USED! / n", x, g_timer_elapsed (timer, null);
}
The Makefile file is as follows: CC = GCC All: $ (cc) `pkg-config --cflags --libs glib-2.0` Until.c -o Until output results:
48 95 95 99 90 24 90 29 78 4 53 87 1 86 7 93 57 88 75 4
30000000 All: 1.47 Seconds WAS Used!
Each object in GLIB has almost one or more * _new functions to create, the timer gtimer is the same as the machine GRAND, and there is a corresponding function to end the object of the object, such as gtimer g_timer_stop, grand g_rand_free . This may be the simplest in the GLIB practical function. Many friends will be at a glance. We should also pay attention to Glib's code style and package skills are unique. This style and skill is enough to make some self-pronged practical SDK sweat, learning to master this style may benefit us. There are several common data structural types and their related operation functions in the data type GLIB, which is a simple example of string type:
#include
Int main (int Argc, char * argv [])
{
Gstring * s;
S = g_string_new ("hello");
g_print ("% s / n", S-> STR);
s = g_string_append (s, "world!");
g_print ("% s / n", S-> STR);
S = g_string_erase (s, 0, 6);
g_print ("% s / n", S-> STR);
s = g_string_prepend (s, "also a");
g_print ("% s / n", S-> STR);
s = g_string_insert (s, 6, "nice");
g_print ("% s / n", S-> STR);
}
The Makefile file is as follows:
CC = GCC
All:
$ (Cc) `pkg-config --cflags --libs glib-2.0` String.c -o str
Below is the output result:
Hello
Hello World!
World!
Also a world!
Also a nice world!
The string has the high frequency in the programming, even the beginners are clear, additional, delete, and insertion, other operational understandings, you can further understand the other more complex operations. GLIB provides a GMEMCHUNK data type that provides a very easy way of operation for a large memory area with a large-purpose memory. The following program demonstrates a simple usage of memory block data types:
#include
Int main (int Argc, char * argv [])
{
GMemchunk * chunk; // Define the memory block
Gchar * MEM [10]; // Defines the array of pointers to atoms
Gint i, j;
// Create a memory block
Chunk = g_mem_chunk_new ("Test Memchunk", 5, 50, g_alloc_and_free); // Name, the length of the atom, the length of the memory block, type
For (i = 0; i <10; i )
{
// Create an object
// MEM [i] = g_chunk_new (gchar, chunk);
MEM [I] = (gchar *) g_mem_chunk_alloc (chunk);
For (j = 0; j <5; j )
{
MEM [i] [j] = 'a' j; / / assigns a pointer in the memory block
}
}
g_mem_chunk_print (chunk); // Displays memory block information
For (i = 0; i <10; i )
{
g_print ("% s / t", MEM [i]); // Displays the content in the memory block
}
For (i = 0; i <10; i )
{
g_mem_chunk_free (chunk, mem [i]); // Release all assigned memory
}
g_mem_chunk_destroy (chunk);
}
The Makefile file is as follows:
CC = GCC
All:
$ (Cc) `pkg-config --cflags --libs glib-2.0` Data1.c -o data1
The following is the output result:
Glib-Info: Test Memchunk: 80 Bytes Using 2 Mem Areas
Abcde Abcde Abcde Abcde Abcde Abcde Abcde Abcde Abcde Abcde ABCDE
Here, this data type is the reason for the application of this runtime processing link by itself. We allocated 50 bytes of space in the program, which actually uses 80 bytes, where it can be seen that it is partially memory space when allocating memory itself. As can be seen from the sample code above, almost all objects in GLIB are structural types of C language, generally named words starting with uppercase letters G, such as GLIST represents two-way linked list, all related operation functions Small-written letter g Draw the underscore lowering words with underscore starting, if the function starting with G_LIST_ * is an operational function related to this, and the first parameter in these functions is the pointer of this object. The data type in GLIB is used in Glib itself, especially in GTK . It is necessary to understand the usage of these data categories. This is a key ring for further flexibility to develop GTK programs, and is in college "Data Structure" is a good review. In the next GOBJECT object system, you will detail the most important component of Glib, and you want this single inherited object system that buys in this C language will help you enter the world of GTK . Reference
Glib's online documentation: http://developer.gnome.org/doc/api/2.0/glib/index.html About the author Song Guowei, Country Primary School English Teacher, "GTK 2.0 Programming Example" (Tsinghua University Press) Author, spare time is committed to applying GTK development Linux graphical interface applications, you can contact him through GWSONG52@sohu.com.