Analysis on glib

Source: Internet
Author: User
Tags gtk mathematical constants natural logarithm uppercase letter


Analysis on glib


Content:
Basic Type
Support for core applications
Functions
Data Type
References
About the author


Related content:
Container Control and layout skills in GTK + 2.0
Application GTK + programming


In the Linux zone, there are:
Tutorial
Tools and products
Code and components
Project
Article


Song Guowei (gwsong52@sohu.com)
May 2003

Glib is the underlying core library of GTK + and gnome engineering. It is a lightweight C library for comprehensive purposes, it provides definitions of common data structures and related processing functions in C language, interesting and practical macros, portable encapsulation, and some runtime capabilities, APIS such as event loops, threads, dynamic calls, and object systems. It can run on Unix-like operating systems such as Linux, HP-UNIX, windows, os2 and BEOs.

Glib requires the support of a thread-supporting operating system and an iconv Conversion Function between character sets. In fact, most modern operating systems have the above two functions.

Glib consists of five parts: basic type, support for core applications, practical functions, data type, and Object System.

The latest version of glib is glib2.2.1. You can download its source code from www.gtk.org. For applications compiled using glib2.0, 'pkg-config-cflags-libs glib-2.0 'should be added to the compilation command during compilation. For example, compile an application named hello. C program, output the executable file named hello, the command is:

gcc `pkg-config -cflags -libs glib-2.0`  hello.c -o hello 

In glib, we treat the three subsystems (gthread), plug-in (gmoudle), and Object System (gobject) differently. during compilation, we must add relevant parameters.

If the object system is used in the program, it should be added during compilation:

`pkg-config --cflags --libs gobject-2.0`

When a thread is used, add:

`pkg-config --cflags --libs gthread-2.0`

When plug-ins are used, add:

`pkg-config --cflags --libs gmoudle-2.0`

Basic Type

Glib consists of basic types, range-specific macros, standard macros, type conversion macros, byte order conversion macros, mathematical constant definitions, and miscellaneous macros. The basic types are introduced here, because they are used in various libraries and software packages related to glib, such as GTK +, gnome, Mono, and other large open source projects.

The basic type is also known as the standard type. Glib encapsulates the data types in C language into their own data types, all starting with a lowercase letter 'G'. For example, gpointer is a pointer type (void *) guint is an unsigned Int. Some of them are modifyable, such as Gint and gchar. They are exactly the same as int and char in C. These data types are used exactly the same as those in C. When you are familiar with them, you will find that they are more flexible and intuitive to understand. Of course, you can directly use the data types in C language, which does not affect compilation of your program.

In addition, range-specific macros and type conversion macros are also commonly used. For example, g_maxint indicates the maximum int type value, and gint_to_pointer (I) is used to convert integer variable I to pointer type. Macro gpointer_to_int (P) convert the pointer Variable P to an integer.

The values true and false of the logic type gboolean are defined in the constant Macro. In addition, g_e indicates the natural logarithm, g_pi indicates the circumference rate, g_pi_2 indicates the circumference rate of 1/2, and other mathematical constants.

Support for core applications

Glib supports core applications, including event loops, memory operations, thread operations, dynamic link library operations, error processing, and logs.

The following code demonstrates a simple application of the three functions: Event loop, memory operation, and thread:

# Include <glib. h> static gmutex * mutex = NULL; static gboolean t1_end = false; static gboolean t2_end = false; typedef struct _ Arg; struct _ Arg {gmainloop * loop; Gint Max ;}; voidrun_1 (Arg * Arg) {int I; for (I = 0; I <Arg-> MAX; I ++) {If (g_mutex_trylock (mutex) = false) {// g_print ("% d: thread 2 locked the mutex/N", I); g_print ("% d: thread 2 locks the mutex object/N", I ); g_mutex_unlock (mutex);} else {g_usleep (10) ;}} t1_end = true;} voi Drun_2 (Arg * Arg) {int I; for (I = 0; I <Arg-> MAX; I ++) {If (g_mutex_trylock (mutex) = false) {// g_print ("% d: thread 1 locked mutex/N", I); g_print ("% d: thread 1 locks the mutex object/N", I ); g_mutex_unlock (mutex);} else {g_usleep (10) ;}} t2_end = true;} void run_3 (Arg * Arg) {(;;) {If (t1_end & t2_end) {g_main_loop_quit (Arg-> loop); break ;}} intmain (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 loop/N"); g_mutex_free (mutex ); g_print ("release mutex object/N"); g_free (ARG); g_print ("memory used to release parameters/N ");}

The MAKEFILE file is as follows:

CC = gccall:$(CC) `pkg-config --cflags --libs glib-2.0 gthread-2.0` loop.c -o loop

The output result is as follows:

0: thread 1 locks the mutex object.
1: thread 2 locks the mutex object
2: thread 1 locks the mutex object.
3: thread 2 locks the mutex object
4: thread 1 locks the mutex object
5: thread 2 locks the mutex object.
6: thread 1 locks the mutex object
7: thread 2 locks the mutex object
8: thread 1 locks the mutex object.
9: thread 2 locks the mutex object.
10: thread 1 locks the mutex object.
Thread 3 Exit the event Loop
Release mutex
Release the memory used by the Parameter

The preceding routine creates three threads, run_1 and run_2 operations are mutually exclusive objects, and run_3 searches for whether the first two threads are finished. If so, execute g_main_loop_quit to exit the event loop. Because the running of the thread is uncertain, it is not necessarily the output result every time.

First, define a structure type to save the object pointer of the created event loop and the maximum number of cycles during thread running. Generally, if the memory is allocated for this data structure, using Arg * Arg = (Arg *) malloc (sizeof (ARG); and using free (ARG) for release; this traditional practice once caused a headache for many beginners of C language, especially when multiple operations are required, glib provides functions such as g_malloc and g_free. The best way is to encapsulate the g_malloc function into a macro g_new. This macro has two parameters, the first is the structure type, and the second is the number of structures to be allocated. This Code only uses an ARG data structure, so it is g_new (ARG, 1 ). Use g_free to release the program at the end of the program.

During thread initialization, the first step is to determine whether the thread initializes the function g_thread_supported. If the return value is false, the thread is not initialized. In this case, g_thread_init must be used for initialization. This is a wise practice.

The event loop gmainloop does not run immediately after being created with g_main_loop_new. After running with g_main_loop_run, you also need to exit with g_main_loop_quit. Otherwise, the loop will continue to run. The parameters of these two functions are gmainloop pointers, the main function does not directly run g_main_loop_quit, but stores it in the function of the thread. This requires your attention.

Functions

Glib contains nearly 20 practical functions, from simple character processing to XML parsing functions that are hard to understand for beginners. Here we introduce two simple functions: Random Number and timing.

The following code demonstrates how to generate a random integer between 1-30000000 and how to calculate the time used for the calculation of accumulated values:

/*. C is used to test practical functions */# include <glib. h> intmain (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 ++) {// generate a random number and display g_print ("% d/T", g_rand_int_range (RAND, 1,100);} g_print ("/N"); g_rand_free (RAND ); // release the random number object // create the timer = g_timer_new (); g_timer_start (timer); // start the timer for (I = 0; I <10000; I ++) for (j = 0; j <3000; j ++) x ++; // accumulative g_timer_stop (timer );/ /Time end // output time result g_print ("% LD/tall: %. 2f seconds was used! /N ", X, g_timer_elapsed (timer, null ));}

The contents of makefile are as follows:

Cc = GCC all: $ (CC) 'pkg-config -- cflags -- libs glib-2.0 'Until. C-o

Output result:

48 95 95 99 90 24 90 29 78 4 53 87 1 86 7 93 57 88 75 430000000 all:1.47 seconds was used!

Almost every object in glib has one or more * _ new functions to create. The timer gtimer is the same as the random grand, and there are also corresponding functions to end the use of objects, for example, gtimer's g_timer_stop and grand's g_rand_free.

This may be the simplest of the two glib practical functions, and many of them will be clear at a glance. We should also note that glib's code style and encapsulation skills are unique. This style and skill is enough to make some self-proclaimed simple and practical sdks feel ashamed, learning to master this style may benefit us a lot.

Data Type

Glib defines more than a dozen common data structure types and their related operation functions. The following is a simple example of the string type:

#include <glib.h>intmain(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 = gccall:$(CC) `pkg-config --cflags --libs glib-2.0 ` string.c -o str

The output result is as follows:

HelloHello World!World!Also a World!Also a Nice World!

The frequency of string compilation is high. Even beginners are familiar with it. After understanding common operations such as append, delete, and insert, you can learn more about other complex operations.

Glib provides a memory block (gmemchunk) data type, which provides a very useful operation mode for large memory areas such as allocation, the following program demonstrates the simple usage of the memory block data type:

# Include <glib. h> intmain (INT argc, char * argv []) {gmemchunk * chunk; // defines the memory block gchar * mem [10]; // define the pointer array Gint I, j pointing to the atom; // create a memory chunk = g_mem_chunk_new ("test memchunk", 5, 50, g_alloc_and_free); // name, atomic length, memory block length, type for (I = 0; I <10; I ++) {// create 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; // assign a value to the pointer in the memory block} g_mem_chunk_print (chunk ); // display the memory block information for (I = 0; I <10; I ++) {g_print ("% S/T", Mem [I]); // display the content in the memory block} for (I = 0; I <10; I ++) {g_mem_chunk_free (chunk, Mem [I]); // release all allocated memory} g_mem_chunk_destroy (chunk );}

The MAKEFILE file is as follows:

CC = gccall:$(CC) `pkg-config --cflags --libs glib-2.0` data1.c -o data1

The output result is as follows:

GLib-INFO: Test MemChunk: 80 bytes using 2 mem areasABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDE

The reason for this data type is that it can be used to better understand the application of the runtime processing process of memory allocation.

We allocate 50 bytes of space in the program, but actually use 80 bytes. We can see that it uses part of the memory space when allocating the memory.

As shown in the sample code above, almost all objects in glib are structured in C language. Generally, they are named words starting with an uppercase letter G. For example, Glist indicates a two-way linked list, all related operation functions start with a lowercase letter, G, and lowercase word, and an underscore. For example, all functions starting with g_list _ * are related operation functions, most of the first parameters in these functions are pointers to this object.

The data types in glib are frequently used in glib, especially GTK +. It is necessary to understand the usage of these data types, this is a key link for further flexible development of GTK + programs and a good review of the data structure section in the university.

In the next gobject object system, we will detail the most important part of glib, The gobject system. We hope that this single-inherited object system established by C language will help you enter the world of GTK +.

References

  • Glib online documentation: http://developer.gnome.org/doc/API/2.0/glib/index.html

About the author

Song Guowei, an English teacher in Rural Primary School, and author of GTK + 2.0 programming example (Tsinghua University Press). He devoted himself to using GTK + to develop Linux graphic interface applications in his spare time, you can contact him through the gwsong52@sohu.com.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.