GLib參考手冊

當前版本為 2.20.4 , 最新在線版本請瀏覽這裡 http://www.gtk.org/api/2.6/glib/index.html.

發佈日期: 2009年11月06日

簡體中文翻譯者(字典排序):

cnkilior
kovchou
lerosua
NULL
wzssyqa
yetist
功夫熊貓

繁體中文轉換並翻譯更新者:

ㄚ琪

項目主頁: http://gtk-doc-cn.googlecode.com

Bug報告: http://code.google.com/p/gtk-doc-cn/issues/entry

本文檔由GADT(Gnome API Document Translation)團隊翻譯, 依照GNU自由文檔許可證 (GFDL)公開發行

GLib基礎

GLib版本訊息 — 檢查GLib版本訊息的變數和函式
基本類型 — GLib 標準類型, 定義的非常易用和簡便
基本類型的限制 — 決定標準類型限制的可移植方法
標準巨集 — 常用的巨集。
類型轉換巨集 — 用指標變數可移植地儲存整數
字節序宏 — 在不同的字元序之間進行轉換的移植方法
Numerical Definitions — mathematical constants, and floating point decomposition
Miscellaneous Macros — specialized macros which are not used often
原子操作 — 基本原子整數和指標操作

標準巨集

標準巨集 — 常用的巨集。

 

一覽表

#include <glib.h>

#define G_OS_WIN32
#define G_OS_BEOS
#define G_OS_UNIX

#define G_DIR_SEPARATOR
#define G_DIR_SEPARATOR_S
#define G_IS_DIR_SEPARATOR (c)
#define G_SEARCHPATH_SEPARATOR
#define G_SEARCHPATH_SEPARATOR_S

#define TRUE
#define FALSE

#define NULL

#define MIN (a, b)
#define MAX (a, b)

#define ABS (a)
#define CLAMP (x, low, high)

#define G_STRUCT_MEMBER (member_type, struct_p, struct_offset)
#define G_STRUCT_MEMBER_P (struct_p, struct_offset)
#define G_STRUCT_OFFSET (struct_type, member)

#define G_MEM_ALIGN

#define G_CONST_RETURN

Description

These macros provide a few commonly-used features.

Details

G_OS_WIN32

#define G_OS_WIN32

This macro is defined only on Windows. So you can bracket Windows-specific code in "#ifdef G_OS_WIN32".


G_OS_BEOS

#define G_OS_BEOS

This macro is defined only on BeOS. So you can bracket BeOS-specific code in "#ifdef G_OS_BEOS".


G_OS_UNIX

#define G_OS_UNIX

This macro is defined only on UNIX. So you can bracket UNIX-specific code in "#ifdef G_OS_UNIX".


G_DIR_SEPARATOR

#define             G_DIR_SEPARATOR

The directory separator character. This is '/' on UNIX machines and '\' under Windows.


G_DIR_SEPARATOR_S

#define             G_DIR_SEPARATOR_S

目錄的分隔字串符號,在UNIX機器上是"/"而在Windows下是 "\"。


G_IS_DIR_SEPARATOR()

#define             G_IS_DIR_SEPARATOR(c)

Checks whether a character is a directory separator. It returns TRUE for '/' on UNIX machines and for '\' or '/' under Windows.

c :

a character

Since 2.6


G_SEARCHPATH_SEPARATOR

#define             G_SEARCHPATH_SEPARATOR

The search path separator character. This is ':' on UNIX machines and ';' under Windows.


G_SEARCHPATH_SEPARATOR_S

#define             G_SEARCHPATH_SEPARATOR_S

The search path separator as a string. This is ":" on UNIX machines and ";" under Windows.


TRUE

#define	TRUE	(!FALSE)

Defines the TRUE value for the gboolean type.


FALSE

#define	FALSE	(0)

Defines the FALSE value for the gboolean type.


NULL

#define             NULL

Defines the standard NULL pointer.


MIN()

#define MIN(a, b)  (((a) < (b)) ? (a) : (b))

Calculates the minimum of a and b.

a :

a numeric value.

b :

a numeric value.

Returns :

the minimum of a and b.

MAX()

#define MAX(a, b)  (((a) > (b)) ? (a) : (b))

Calculates the maximum of a and b.

a :

a numeric value.

b :

a numeric value.

Returns :

the maximum of a and b.

ABS()

#define ABS(a)	   (((a) < 0) ? -(a) : (a))

Calculates the absolute value of a. The absolute value is simply the number with any negative sign taken away.

For example,

  • ABS(-10) is 10.

  • ABS(10) is also 10.

 

a :

a numeric value.

Returns :

the absolute value of a.

CLAMP()

#define CLAMP(x, low, high)  (((x) > (high)) ? (high) : (((x) < (low)) ? (low) : (x)))

Ensures that x is between the limits set by low and high. If low is greater than high the result is undefined.

For example,

  • CLAMP(5, 10, 15) is 10.

  • CLAMP(15, 5, 10) is 10.

  • CLAMP(20, 15, 25) is 20.

 

x :

the value to clamp.

low :

the minimum value allowed.

high :

the maximum value allowed.

Returns :

the value of x clamped to the range between low and high.

G_STRUCT_MEMBER()

#define             G_STRUCT_MEMBER(member_type, struct_p, struct_offset)

Returns a member of a structure at a given offset, using the given type.

member_type :

the type of the struct field.

struct_p :

a pointer to a struct.

struct_offset :

the offset of the field from the start of the struct, in bytes.

Returns :

the struct member.

G_STRUCT_MEMBER_P()

#define             G_STRUCT_MEMBER_P(struct_p, struct_offset)

Returns an untyped pointer to a given offset of a struct.

struct_p :

a pointer to a struct.

struct_offset :

the offset from the start of the struct, in bytes.

Returns :

an untyped pointer to struct_p plus struct_offset bytes.

G_STRUCT_OFFSET()

#define             G_STRUCT_OFFSET(struct_type, member)

Returns the offset, in bytes, of a member of a struct.

struct_type :

a structure type, e.g. GtkWidget.

member :

a field in the structure, e.g. window.

Returns :

the offset of member from the start of struct_type.

G_MEM_ALIGN

#define             G_MEM_ALIGN

Indicates the number of bytes to which memory will be aligned on the current platform.


G_CONST_RETURN

#define             G_CONST_RETURN

If G_DISABLE_CONST_RETURNS is defined, this macro expands to nothing. By default, the macro expands to const. The macro should be used in place of const for functions that return a value that should not be modified. The purpose of this macro is to allow us to turn on const for returned constant strings by default, while allowing programmers who find that annoying to turn it off. This macro should only be used for return values and for out parameters, it doesn't make sense for in parameters.

GLib核心應用支援

The Main Event Loop — manages all available sources of events
Threads — 執行緒抽象;包括執行緒、不同互斥、狀況和執行緒私有資料
Thread Pools — pools of threads to execute work concurrently
Asynchronous Queues — asynchronous communication between threads
模組的動態載入 — portable method for dynamically loading 'plug-ins'
記憶體配置 — 一般的記憶體處理
IO Channels — portable support for using files, pipes and sockets
Error Reporting — a system for reporting errors
訊息輸出跟除錯函式 — functions to output messages and help debug applications
訊息記錄 — versatile support for logging messages with different levels of importance

記憶體配置

記憶體配置 — 一般的記憶體處理

 

一覽表

#include <glib.h>

#define g_new (struct_type, n_structs)
#define g_new0 (struct_type, n_structs)
#define g_renew (struct_type, mem, n_structs)
#define g_try_new (struct_type, n_structs)
#define g_try_new0 (struct_type, n_structs)
#define g_try_renew (struct_type, mem, n_structs)

gpointer g_malloc (gsize n_bytes);
gpointer g_malloc0 (gsize n_bytes);
gpointer g_realloc (gpointer mem,
gsize n_bytes);
gpointer g_try_malloc (gsize n_bytes);
gpointer g_try_malloc0 (gsize n_bytes);
gpointer g_try_realloc (gpointer mem,
gsize n_bytes);
gpointer g_malloc_n (gsize n_blocks,
gsize n_block_bytes);
gpointer g_malloc0_n (gsize n_blocks,
gsize n_block_bytes);
gpointer g_realloc_n (gpointer mem,
gsize n_blocks,
gsize n_block_bytes);
gpointer g_try_malloc_n (gsize n_blocks,
gsize n_block_bytes);
gpointer g_try_malloc0_n (gsize n_blocks,
gsize n_block_bytes);
gpointer g_try_realloc_n (gpointer mem,
gsize n_blocks,
gsize n_block_bytes);

void g_free (gpointer mem);
extern gboolean g_mem_gc_friendly;

#define g_alloca (size)
#define g_newa (struct_type, n_structs)

#define g_memmove (dest,src,len)
gpointer g_memdup (gconstpointer mem,
guint byte_size);

GMemVTable;
void g_mem_set_vtable (GMemVTable *vtable);
gboolean g_mem_is_system_malloc (void);

extern GMemVTable *glib_mem_profiler_table;
void g_mem_profile (void);

說明

這些函式提供了配置跟釋放記憶體的支援。

注意

假如任何配置記憶體的呼叫失敗,程式就會終止,這也表示假如呼叫成功就不需要檢查。

注意

g_malloc()g_free()malloc()free(),以及(假如你使用C++)new跟delete和new[]跟delete[]配對在一起是重要的,否則會有壞事情可能發生,因為這些配置器使用不同的記憶池(跟new/delete呼叫的建構子跟解構子),另見 g_mem_set_vtable()

細節

g_new()

#define             g_new(struct_type, n_structs)

Allocates n_structs elements of type struct_type. The returned pointer is cast to a pointer to the given type. If n_structs is 0 it returns NULL. Care is taken to avoid overflow when calculating the size of the allocated block.

Since the returned pointer is already casted to the right type, it is normally unnecessary to cast it explicitly, and doing so might hide memory allocation errors.

struct_type :

the type of the elements to allocate

n_structs :

the number of elements to allocate

Returns :

a pointer to the allocated memory, cast to a pointer to struct_type

g_new0()

#define             g_new0(struct_type, n_structs)

Allocates n_structs elements of type struct_type, initialized to 0's. The returned pointer is cast to a pointer to the given type. If n_structs is 0 it returns NULL. Care is taken to avoid overflow when calculating the size of the allocated block.

Since the returned pointer is already casted to the right type, it is normally unnecessary to cast it explicitly, and doing so might hide memory allocation errors.

struct_type :

the type of the elements to allocate.

n_structs :

the number of elements to allocate.

Returns :

a pointer to the allocated memory, cast to a pointer to struct_type.

g_renew()

#define             g_renew(struct_type, mem, n_structs)

Reallocates the memory pointed to by mem, so that it now has space for n_structs elements of type struct_type. It returns the new address of the memory, which may have been moved. Care is taken to avoid overflow when calculating the size of the allocated block.

struct_type :

the type of the elements to allocate

mem :

the currently allocated memory

n_structs :

the number of elements to allocate

Returns :

a pointer to the new allocated memory, cast to a pointer to struct_type

g_try_new()

#define             g_try_new(struct_type, n_structs)

Attempts to allocate n_structs elements of type struct_type, and returns NULL on failure. Contrast with g_new(), which aborts the program on failure. The returned pointer is cast to a pointer to the given type. The function returns NULL when n_structs is 0 of if an overflow occurs.

struct_type :

the type of the elements to allocate

n_structs :

the number of elements to allocate

Returns :

a pointer to the allocated memory, cast to a pointer to struct_type

Since 2.8


g_try_new0()

#define             g_try_new0(struct_type, n_structs)

Attempts to allocate n_structs elements of type struct_type, initialized to 0's, and returns NULL on failure. Contrast with g_new0(), which aborts the program on failure. The returned pointer is cast to a pointer to the given type. The function returns NULL when n_structs is 0 of if an overflow occurs.

struct_type :

the type of the elements to allocate

n_structs :

the number of elements to allocate

Returns :

a pointer to the allocated memory, cast to a pointer to struct_type

Since 2.8


g_try_renew()

#define             g_try_renew(struct_type, mem, n_structs)

Attempts to reallocate the memory pointed to by mem, so that it now has space for n_structs elements of type struct_type, and returns NULL on failure. Contrast with g_renew(), which aborts the program on failure. It returns the new address of the memory, which may have been moved. The function returns NULL if an overflow occurs.

struct_type :

the type of the elements to allocate

mem :

the currently allocated memory

n_structs :

the number of elements to allocate

Returns :

a pointer to the new allocated memory, cast to a pointer to struct_type

Since 2.8


g_malloc ()

gpointer            g_malloc                            (gsize n_bytes);

Allocates n_bytes bytes of memory. If n_bytes is 0 it returns NULL.

n_bytes :

the number of bytes to allocate

Returns :

a pointer to the allocated memory

g_malloc0 ()

gpointer            g_malloc0                           (gsize n_bytes);

Allocates n_bytes bytes of memory, initialized to 0's. If n_bytes is 0 it returns NULL.

n_bytes :

the number of bytes to allocate

Returns :

a pointer to the allocated memory

g_realloc ()

gpointer            g_realloc                           (gpointer mem,
gsize n_bytes);

Reallocates the memory pointed to by mem, so that it now has space for n_bytes bytes of memory. It returns the new address of the memory, which may have been moved. mem may be NULL, in which case it's considered to have zero-length. n_bytes may be 0, in which case NULL will be returned and mem will be freed unless it is NULL.

mem :

the memory to reallocate

n_bytes :

new size of the memory in bytes

Returns :

the new address of the allocated memory

g_try_malloc ()

gpointer            g_try_malloc                        (gsize n_bytes);

Attempts to allocate n_bytes, and returns NULL on failure. Contrast with g_malloc(), which aborts the program on failure.

n_bytes :

number of bytes to allocate.

Returns :

the allocated memory, or NULL.

g_try_malloc0 ()

gpointer            g_try_malloc0                       (gsize n_bytes);

Attempts to allocate n_bytes, initialized to 0's, and returns NULL on failure. Contrast with g_malloc0(), which aborts the program on failure.

n_bytes :

number of bytes to allocate

Returns :

the allocated memory, or NULL

Since 2.8


g_try_realloc ()

gpointer            g_try_realloc                       (gpointer mem,
gsize n_bytes);

Attempts to realloc mem to a new size, n_bytes, and returns NULL on failure. Contrast with g_realloc(), which aborts the program on failure. If mem is NULL, behaves the same as g_try_malloc().

mem :

previously-allocated memory, or NULL.

n_bytes :

number of bytes to allocate.

Returns :

the allocated memory, or NULL.

g_malloc_n ()

gpointer            g_malloc_n                          (gsize n_blocks,
gsize n_block_bytes);

This function is similar to g_malloc(), allocating (n_blocks * n_block_bytes) bytes, but care is taken to detect possible overflow during multiplication.

n_blocks :

the number of blocks to allocate

n_block_bytes :

the size of each block in bytes

Returns :

a pointer to the allocated memory

Since 2.24


g_malloc0_n ()

gpointer            g_malloc0_n                         (gsize n_blocks,
gsize n_block_bytes);

This function is similar to g_malloc0(), allocating (n_blocks * n_block_bytes) bytes, but care is taken to detect possible overflow during multiplication.

n_blocks :

the number of blocks to allocate

n_block_bytes :

the size of each block in bytes

Returns :

a pointer to the allocated memory

Since 2.24


g_realloc_n ()

gpointer            g_realloc_n                         (gpointer mem,
gsize n_blocks,
gsize n_block_bytes);

This function is similar to g_realloc(), allocating (n_blocks * n_block_bytes) bytes, but care is taken to detect possible overflow during multiplication.

mem :

the memory to reallocate

n_blocks :

the number of blocks to allocate

n_block_bytes :

the size of each block in bytes

Returns :

the new address of the allocated memory

Since 2.24


g_try_malloc_n ()

gpointer            g_try_malloc_n                      (gsize n_blocks,
gsize n_block_bytes);

This function is similar to g_try_malloc(), allocating (n_blocks * n_block_bytes) bytes, but care is taken to detect possible overflow during multiplication.

n_blocks :

the number of blocks to allocate

n_block_bytes :

the size of each block in bytes

Returns :

the allocated memory, or NULL.

Since 2.24


g_try_malloc0_n ()

gpointer            g_try_malloc0_n                     (gsize n_blocks,
gsize n_block_bytes);

This function is similar to g_try_malloc0(), allocating (n_blocks * n_block_bytes) bytes, but care is taken to detect possible overflow during multiplication.

n_blocks :

the number of blocks to allocate

n_block_bytes :

the size of each block in bytes

Returns :

the allocated memory, or NULL

Since 2.24


g_try_realloc_n ()

gpointer            g_try_realloc_n                     (gpointer mem,
gsize n_blocks,
gsize n_block_bytes);

This function is similar to g_try_realloc(), allocating (n_blocks * n_block_bytes) bytes, but care is taken to detect possible overflow during multiplication.

mem :

previously-allocated memory, or NULL.

n_blocks :

the number of blocks to allocate

n_block_bytes :

the size of each block in bytes

Returns :

the allocated memory, or NULL.

Since 2.24


g_free ()

void                g_free                              (gpointer mem);

釋放指向mem的記憶體,假如memNULL它就只是簡單的傳回。

mem :

記憶體釋放

g_mem_gc_friendly

extern gboolean g_mem_gc_friendly;

This variable is TRUE if the G_DEBUG environment variable includes the key gc-friendly.


g_alloca()

#define             g_alloca(size)

Allocates size bytes on the stack; these bytes will be freed when the current stack frame is cleaned up. This macro essentially just wraps the alloca() function present on most UNIX variants. Thus it provides the same advantages and pitfalls as alloca():

 

+ alloca() is very fast, as on most systems it's implemented by just adjusting the stack pointer register.

 

+ It doesn't cause any memory fragmentation, within its scope, separate alloca() blocks just build up and are released together at function end.

 

- Allocation sizes have to fit into the current stack frame. For instance in a threaded environment on Linux, the per-thread stack size is limited to 2 Megabytes, so be sparse with alloca() uses.

 

- Allocation failure due to insufficient stack space is not indicated with a NULL return like e.g. with malloc(). Instead, most systems probably handle it the same way as out of stack space situations from infinite function recursion, i.e. with a segmentation fault.

 

- Special care has to be taken when mixing alloca() with GNU C variable sized arrays. Stack space allocated with alloca() in the same scope as a variable sized array will be freed together with the variable sized array upon exit of that scope, and not upon exit of the enclosing function scope.

 

size :

number of bytes to allocate.

Returns :

space for size bytes, allocated on the stack

g_newa()

#define             g_newa(struct_type, n_structs)

Wraps g_alloca() in a more typesafe manner.

struct_type :

Type of memory chunks to be allocated

n_structs :

Number of chunks to be allocated

Returns :

Pointer to stack space for n_structs chunks of type struct_type

g_memmove()

#define             g_memmove(dest,src,len)

Copies a block of memory len bytes long, from src to dest. The source and destination areas may overlap.

In order to use this function, you must include string.h yourself, because this macro will typically simply resolve to memmove() and GLib does not include string.h for you.

 

dest :

the destination address to copy the bytes to.

src :

the source address to copy the bytes from.

len :

the number of bytes to copy.

g_memdup ()

gpointer            g_memdup                            (gconstpointer mem,
guint byte_size);

Allocates byte_size bytes of memory, and copies byte_size bytes into it from mem. If mem is NULL it returns NULL.

mem :

the memory to copy.

byte_size :

the number of bytes to copy.

Returns :

a pointer to the newly-allocated copy of the memory, or NULL if mem is NULL.

GMemVTable

typedef struct {
gpointer (*malloc) (gsize n_bytes);
gpointer (*realloc) (gpointer mem,
gsize n_bytes);
void (*free) (gpointer mem);
/* optional; set to NULL if not used ! */
gpointer (*calloc) (gsize n_blocks,
gsize n_block_bytes);
gpointer (*try_malloc) (gsize n_bytes);
gpointer (*try_realloc) (gpointer mem,
gsize n_bytes);
} GMemVTable;

A set of functions used to perform memory allocation. The same GMemVTable must be used for all allocations in the same program; a call to g_mem_set_vtable(), if it exists, should be prior to any use of GLib.

malloc ()

function to use for allocating memory.

realloc ()

function to use for reallocating memory.

free ()

function to use to free memory.

calloc ()

function to use for allocating zero-filled memory.

try_malloc ()

function to use for allocating memory without a default error handler.

try_realloc ()

function to use for reallocating memory without a default error handler.

g_mem_set_vtable ()

void                g_mem_set_vtable                    (GMemVTable *vtable);

Sets the GMemVTable to use for memory allocation. You can use this to provide custom memory allocation routines. This function must be called before using any other GLib functions. The vtable only needs to provide malloc(), realloc(), and free() functions; GLib can provide default implementations of the others. The malloc() and realloc() implementations should return NULL on failure, GLib will handle error-checking for you. vtable is copied, so need not persist after this function has been called.

vtable :

table of memory allocation routines.

g_mem_is_system_malloc ()

gboolean            g_mem_is_system_malloc              (void);

Checks whether the allocator used by g_malloc() is the system's malloc implementation. If it returns TRUE memory allocated with malloc() can be used interchangeable with memory allocated using g_malloc(). This function is useful for avoiding an extra copy of allocated memory returned by a non-GLib-based API.

A different allocator can be set using g_mem_set_vtable().

 

Returns :

if TRUE, malloc() and g_malloc() can be mixed.

glib_mem_profiler_table

extern GMemVTable	*glib_mem_profiler_table;

A GMemVTable containing profiling variants of the memory allocation functions. Use them together with g_mem_profile() in order to get information about the memory allocation pattern of your program.


g_mem_profile ()

void                g_mem_profile                       (void);

Outputs a summary of memory usage.

It outputs the frequency of allocations of different sizes, the total number of bytes which have been allocated, the total number of bytes which have been freed, and the difference between the previous two values, i.e. the number of bytes still in use.

Note that this function will not output anything unless you have previously installed the glib_mem_profiler_table with g_mem_set_vtable().

Threads

Threads — 執行緒抽象;包括執行緒、不同互斥、狀況和執行緒私有資料

 

一覽表

#include <glib.h>

#define G_THREADS_ENABLED
#define G_THREADS_IMPL_POSIX
#define G_THREADS_IMPL_NONE

#define G_THREAD_ERROR
enum GThreadError;

GThreadFunctions;
void g_thread_init (GThreadFunctions *vtable);
gboolean g_thread_supported ();
gboolean g_thread_get_initialized (void);

gpointer (*GThreadFunc) (gpointer data);
enum GThreadPriority;
GThread;
GThread * g_thread_create (GThreadFunc func,
gpointer data,
gboolean joinable,
GError **error);
GThread* g_thread_create_full (GThreadFunc func,
gpointer data,
gulong stack_size,
gboolean joinable,
gboolean bound,
GThreadPriority priority,
GError **error);
GThread* g_thread_self (void);
gpointer g_thread_join (GThread *thread);
void g_thread_set_priority (GThread *thread,
GThreadPriority priority);
void g_thread_yield ();
void g_thread_exit (gpointer retval);
void g_thread_foreach (GFunc thread_func,
gpointer user_data);

GMutex;
GMutex * g_mutex_new ();
void g_mutex_lock (GMutex *mutex);
gboolean g_mutex_trylock (GMutex *mutex);
void g_mutex_unlock (GMutex *mutex);
void g_mutex_free (GMutex *mutex);

GStaticMutex;
#define G_STATIC_MUTEX_INIT
void g_static_mutex_init (GStaticMutex *mutex);
void g_static_mutex_lock (GStaticMutex *mutex);
gboolean g_static_mutex_trylock (GStaticMutex *mutex);
void g_static_mutex_unlock (GStaticMutex *mutex);
GMutex * g_static_mutex_get_mutex (GStaticMutex *mutex);
void g_static_mutex_free (GStaticMutex *mutex);

#define G_LOCK_DEFINE (name)
#define G_LOCK_DEFINE_STATIC (name)
#define G_LOCK_EXTERN (name)
#define G_LOCK (name)
#define G_TRYLOCK (name)
#define G_UNLOCK (name)

GStaticRecMutex;
#define G_STATIC_REC_MUTEX_INIT
void g_static_rec_mutex_init (GStaticRecMutex *mutex);
void g_static_rec_mutex_lock (GStaticRecMutex *mutex);
gboolean g_static_rec_mutex_trylock (GStaticRecMutex *mutex);
void g_static_rec_mutex_unlock (GStaticRecMutex *mutex);
void g_static_rec_mutex_lock_full (GStaticRecMutex *mutex,
guint depth);
guint g_static_rec_mutex_unlock_full (GStaticRecMutex *mutex);
void g_static_rec_mutex_free (GStaticRecMutex *mutex);

GStaticRWLock;
#define G_STATIC_RW_LOCK_INIT
void g_static_rw_lock_init (GStaticRWLock *lock);
void g_static_rw_lock_reader_lock (GStaticRWLock *lock);
gboolean g_static_rw_lock_reader_trylock (GStaticRWLock *lock);
void g_static_rw_lock_reader_unlock (GStaticRWLock *lock);
void g_static_rw_lock_writer_lock (GStaticRWLock *lock);
gboolean g_static_rw_lock_writer_trylock (GStaticRWLock *lock);
void g_static_rw_lock_writer_unlock (GStaticRWLock *lock);
void g_static_rw_lock_free (GStaticRWLock *lock);

GCond;
GCond* g_cond_new ();
void g_cond_signal (GCond *cond);
void g_cond_broadcast (GCond *cond);
void g_cond_wait (GCond *cond,
GMutex *mutex);
gboolean g_cond_timed_wait (GCond *cond,
GMutex *mutex,
GTimeVal *abs_time);
void g_cond_free (GCond *cond);

GPrivate;
GPrivate* g_private_new (GDestroyNotify destructor);
gpointer g_private_get (GPrivate *private_key);
void g_private_set (GPrivate *private_key,
gpointer data);

GStaticPrivate;
#define G_STATIC_PRIVATE_INIT
void g_static_private_init (GStaticPrivate *private_key);
gpointer g_static_private_get (GStaticPrivate *private_key);
void g_static_private_set (GStaticPrivate *private_key,
gpointer data,
GDestroyNotify notify);
void g_static_private_free (GStaticPrivate *private_key);

GOnce;
enum GOnceStatus;
#define G_ONCE_INIT
#define g_once (once,
func,
arg)
gboolean g_once_init_enter (volatile gsize *value_location);
void g_once_init_leave (volatile gsize *value_location,
gsize initialization_value);

void g_bit_lock (volatile gint *address,
gint lock_bit);
gboolean g_bit_trylock (volatile gint *address,
gint lock_bit);
void g_bit_unlock (volatile gint *address,
gint lock_bit);

Description

Threads act almost like processes, but unlike processes all threads of one process share the same memory. This is good, as it provides easy communication between the involved threads via this shared memory, and it is bad, because strange things (so called "Heisenbugs") might happen if the program is not carefully designed. In particular, due to the concurrent nature of threads, no assumptions on the order of execution of code running in different threads can be made, unless order is explicitly forced by the programmer through synchronization primitives.

The aim of the thread related functions in GLib is to provide a portable means for writing multi-threaded software. There are primitives for mutexes to protect the access to portions of memory (GMutex, GStaticMutex, G_LOCK_DEFINE, GStaticRecMutex and GStaticRWLock). There are primitives for condition variables to allow synchronization of threads (GCond). There are primitives for thread-private data - data that every thread has a private instance of (GPrivate, GStaticPrivate). Last but definitely not least there are primitives to portably create and manage threads (GThread).

The threading system is initialized with g_thread_init(), which takes an optional custom thread implementation or NULL for the default implementation. If you want to call g_thread_init() with a non-NULL argument this must be done before executing any other GLib functions (except g_mem_set_vtable()). This is a requirement even if no threads are in fact ever created by the process.

Calling g_thread_init() with a NULL argument is somewhat more relaxed. You may call any other glib functions in the main thread before g_thread_init() as long as g_thread_init() is not called from a glib callback, or with any locks held. However, many libraries above glib does not support late initialization of threads, so doing this should be avoided if possible.

Please note that since version 2.24 the GObject initialization function g_type_init() initializes threads (with a NULL argument), so most applications, including those using Gtk+ will run with threads enabled. If you want a special thread implementation, make sure you call g_thread_init() before g_type_init() is called.

After calling g_thread_init(), GLib is completely thread safe (all global data is automatically locked), but individual data structure instances are not automatically locked for performance reasons. So, for example you must coordinate accesses to the same GHashTable from multiple threads. The two notable exceptions from this rule are GMainLoop and GAsyncQueue, which are threadsafe and need no further application-level locking to be accessed from multiple threads.

To help debugging problems in multithreaded applications, GLib supports error-checking mutexes that will give you helpful error messages on common problems. To use error-checking mutexes, define the symbol G_ERRORCHECK_MUTEXES when compiling the application.

Details

G_THREADS_ENABLED

#define G_THREADS_ENABLED

This macro is defined if GLib was compiled with thread support. This does not necessarily mean that there is a thread implementation available, but it does mean that the infrastructure is in place and that once you provide a thread implementation to g_thread_init(), GLib will be multi-thread safe. If G_THREADS_ENABLED is not defined, then Glib is not, and cannot be, multi-thread safe.


G_THREADS_IMPL_POSIX

#define G_THREADS_IMPL_POSIX

This macro is defined if POSIX style threads are used.


G_THREADS_IMPL_NONE

#define G_THREADS_IMPL_NONE

This macro is defined if no thread implementation is used. You can, however, provide one to g_thread_init() to make GLib multi-thread safe.


G_THREAD_ERROR

#define G_THREAD_ERROR g_thread_error_quark ()

The error domain of the GLib thread subsystem.


enum GThreadError

typedef enum
{
G_THREAD_ERROR_AGAIN /* Resource temporarily unavailable */
} GThreadError;

Possible errors of thread related functions.

G_THREAD_ERROR_AGAIN

a thread couldn't be created due to resource shortage. Try again later.

GThreadFunctions

typedef struct {
GMutex* (*mutex_new) (void);
void (*mutex_lock) (GMutex *mutex);
gboolean (*mutex_trylock) (GMutex *mutex);
void (*mutex_unlock) (GMutex *mutex);
void (*mutex_free) (GMutex *mutex);
GCond* (*cond_new) (void);
void (*cond_signal) (GCond *cond);
void (*cond_broadcast) (GCond *cond);
void (*cond_wait) (GCond *cond,
GMutex *mutex);
gboolean (*cond_timed_wait) (GCond *cond,
GMutex *mutex,
GTimeVal *end_time);
void (*cond_free) (GCond *cond);
GPrivate* (*private_new) (GDestroyNotify destructor);
gpointer (*private_get) (GPrivate *private_key);
void (*private_set) (GPrivate *private_key,
gpointer data);
void (*thread_create) (GThreadFunc func,
gpointer data,
gulong stack_size,
gboolean joinable,
gboolean bound,
GThreadPriority priority,
gpointer thread,
GError **error);
void (*thread_yield) (void);
void (*thread_join) (gpointer thread);
void (*thread_exit) (void);
void (*thread_set_priority)(gpointer thread,
GThreadPriority priority);
void (*thread_self) (gpointer thread);
gboolean (*thread_equal) (gpointer thread1,
gpointer thread2);
} GThreadFunctions;

This function table is used by g_thread_init() to initialize the thread system. The functions in the table are directly used by their g_* prepended counterparts (described in this document). For example, if you call g_mutex_new() then mutex_new() from the table provided to g_thread_init() will be called.

 

Note

Do not use this struct unless you know what you are doing.

 

mutex_new ()

virtual function pointer for g_mutex_new()

mutex_lock ()

virtual function pointer for g_mutex_lock()

mutex_trylock ()

virtual function pointer for g_mutex_trylock()

mutex_unlock ()

virtual function pointer for g_mutex_unlock()

mutex_free ()

virtual function pointer for g_mutex_free()

cond_new ()

virtual function pointer for g_cond_new()

cond_signal ()

virtual function pointer for g_cond_signal()

cond_broadcast ()

virtual function pointer for g_cond_broadcast()

cond_wait ()

virtual function pointer for g_cond_wait()

cond_timed_wait ()

virtual function pointer for g_cond_timed_wait()

cond_free ()

virtual function pointer for g_cond_free()

private_new ()

virtual function pointer for g_private_new()

private_get ()

virtual function pointer for g_private_get()

private_set ()

virtual function pointer for g_private_set()

thread_create ()

virtual function pointer for g_thread_create()

thread_yield ()

virtual function pointer for g_thread_yield()

thread_join ()

virtual function pointer for g_thread_join()

thread_exit ()

virtual function pointer for g_thread_exit()

thread_set_priority ()

virtual function pointer for g_thread_set_priority()

thread_self ()

virtual function pointer for g_thread_self()

thread_equal ()

used internally by recursive mutex locks and by some assertion checks

g_thread_init ()

void                g_thread_init                       (GThreadFunctions *vtable);

假如你從一個以上的執行緒來使用,你必須呼叫g_thread_init()來初始化執行緒系統,大部分的時間你只須要呼叫call g_thread_init (NULL)

 

注意

不要呼叫沒有NULL參數的g_thread_init() 除非你真的知道你在做什麼。

 

 

注意

g_thread_init() 一定不能從GLib作為回呼直接或間接地被呼叫,而且在呼叫 g_thread_init()時沒有互斥會被鎖住。

 

 

注意

g_thread_init() 改變是以GTimer 測量經過時間來做,因此,當g_thread_init()被呼叫時正在執行的計時器可能報告不可靠的時間。

 

g_thread_init() 可以允許呼叫多次(2.24版以後),但是除了第一次呼叫以外不會有什麼事發生,假如參數沒有NULL會有一個警告印出,否則其餘參數會被忽略。

假如沒有執行緒系統而且vtableNULL 或假如並非所有vtable are 元素是非NULL的,那麼g_thread_init() 會終止。

 

注意

要在程式中使用g_thread_init(),你必須函式庫來連結,命令是這樣:pkg-config --libs gthread-2.0 ,並不是所有其它GLib的執行緒相關的函式都這樣,它們不需要連結執行緒的函式庫。

 

vtable :

型別GThreadFunctions的函式資料表,用來提供進入點給執行緒系統使用。

g_thread_supported ()

gboolean            g_thread_supported                  ();

This function returns TRUE if the thread system is initialized, and FALSE if it is not.

 

Note

This function is actually a macro. Apart from taking the address of it you can however use it as if it was a function.

 

Returns :

TRUE, if the thread system is initialized.

g_thread_get_initialized ()

gboolean            g_thread_get_initialized            (void);

Indicates if g_thread_init() has been called.

Returns :

TRUE if threads have been initialized.

Since 2.20


GThreadFunc ()

gpointer            (*GThreadFunc)                      (gpointer data);

Specifies the type of the func functions passed to g_thread_create() or g_thread_create_full().

data :

data passed to the thread.

Returns :

the return value of the thread, which will be returned by g_thread_join().

enum GThreadPriority

typedef enum
{
G_THREAD_PRIORITY_LOW,
G_THREAD_PRIORITY_NORMAL,
G_THREAD_PRIORITY_HIGH,
G_THREAD_PRIORITY_URGENT
} GThreadPriority;

Specifies the priority of a thread.

 

Note

It is not guaranteed that threads with different priorities really behave accordingly. On some systems (e.g. Linux) there are no thread priorities. On other systems (e.g. Solaris) there doesn't seem to be different scheduling for different priorities. All in all try to avoid being dependent on priorities.

 

G_THREAD_PRIORITY_LOW

a priority lower than normal

G_THREAD_PRIORITY_NORMAL

the default priority

G_THREAD_PRIORITY_HIGH

a priority higher than normal

G_THREAD_PRIORITY_URGENT

the highest priority

GThread

typedef struct {
} GThread;

The GThread struct represents a running thread. It has three public read-only members, but the underlying struct is bigger, so you must not copy this struct.

 

Note

Resources for a joinable thread are not fully released until g_thread_join() is called for that thread.

 


g_thread_create ()

GThread *           g_thread_create                     (GThreadFunc func,
gpointer data,
gboolean joinable,
GError **error);

This function creates a new thread with the default priority.

If joinable is TRUE, you can wait for this threads termination calling g_thread_join(). Otherwise the thread will just disappear when it terminates.

The new thread executes the function func with the argument data. If the thread was created successfully, it is returned.

error can be NULL to ignore errors, or non-NULL to report errors. The error is set, if and only if the function returns NULL.

func :

a function to execute in the new thread.

data :

an argument to supply to the new thread.

joinable :

should this thread be joinable?

error :

return location for error.

Returns :

the new GThread on success.

g_thread_create_full ()

GThread*            g_thread_create_full                (GThreadFunc func,
gpointer data,
gulong stack_size,
gboolean joinable,
gboolean bound,
GThreadPriority priority,
GError **error);

This function creates a new thread with the priority priority. If the underlying thread implementation supports it, the thread gets a stack size of stack_size or the default value for the current platform, if stack_size is 0.

If joinable is TRUE, you can wait for this threads termination calling g_thread_join(). Otherwise the thread will just disappear when it terminates. If bound is TRUE, this thread will be scheduled in the system scope, otherwise the implementation is free to do scheduling in the process scope. The first variant is more expensive resource-wise, but generally faster. On some systems (e.g. Linux) all threads are bound.

The new thread executes the function func with the argument data. If the thread was created successfully, it is returned.

error can be NULL to ignore errors, or non-NULL to report errors. The error is set, if and only if the function returns NULL.

 

Note

It is not guaranteed that threads with different priorities really behave accordingly. On some systems (e.g. Linux) there are no thread priorities. On other systems (e.g. Solaris) there doesn't seem to be different scheduling for different priorities. All in all try to avoid being dependent on priorities. Use G_THREAD_PRIORITY_NORMAL here as a default.

 

 

Note

Only use g_thread_create_full() if you really can't use g_thread_create() instead. g_thread_create() does not take stack_size, bound, and priority as arguments, as they should only be used in cases in which it is unavoidable.

 

func :

a function to execute in the new thread.

data :

an argument to supply to the new thread.

stack_size :

a stack size for the new thread.

joinable :

should this thread be joinable?

bound :

should this thread be bound to a system thread?

priority :

a priority for the thread.

error :

return location for error.

Returns :

the new GThread on success.

g_thread_self ()

GThread*            g_thread_self                       (void);

This functions returns the GThread corresponding to the calling thread.

Returns :

the current thread.

g_thread_join ()

gpointer            g_thread_join                       (GThread *thread);

Waits until thread finishes, i.e. the function func, as given to g_thread_create(), returns or g_thread_exit() is called by thread. All resources of thread including the GThread struct are released. thread must have been created with joinable=TRUE in g_thread_create(). The value returned by func or given to g_thread_exit() by thread is returned by this function.

thread :

a GThread to be waited for.

Returns :

the return value of the thread.

g_thread_set_priority ()

void                g_thread_set_priority               (GThread *thread,
GThreadPriority priority);

Changes the priority of thread to priority.

 

Note

It is not guaranteed that threads with different priorities really behave accordingly. On some systems (e.g. Linux) there are no thread priorities. On other systems (e.g. Solaris) there doesn't seem to be different scheduling for different priorities. All in all try to avoid being dependent on priorities.

 

thread :

a GThread.

priority :

a new priority for thread.

g_thread_yield ()

void                g_thread_yield                      ();

Gives way to other threads waiting to be scheduled.

This function is often used as a method to make busy wait less evil. But in most cases you will encounter, there are better methods to do that. So in general you shouldn't use this function.


g_thread_exit ()

void                g_thread_exit                       (gpointer retval);

Exits the current thread. If another thread is waiting for that thread using g_thread_join() and the current thread is joinable, the waiting thread will be woken up and get retval as the return value of g_thread_join(). If the current thread is not joinable, retval is ignored. Calling

 

1
g_thread_exit (retval);

 

is equivalent to returning retval from the function func, as given to g_thread_create().

 

Note

Never call g_thread_exit() from within a thread of a GThreadPool, as that will mess up the bookkeeping and lead to funny and unwanted results.

 

retval :

the return value of this thread.

g_thread_foreach ()

void                g_thread_foreach                    (GFunc thread_func,
gpointer user_data);

Call thread_func on all existing GThread structures. Note that threads may decide to exit while thread_func is running, so without intimate knowledge about the lifetime of foreign threads, thread_func shouldn't access the GThread* pointer passed in as first argument. However, thread_func will not be called for threads which are known to have exited already.

Due to thread lifetime checks, this function has an execution complexity which is quadratic in the number of existing threads.

thread_func :

function to call for all GThread structures

user_data :

second argument to thread_func

Since 2.10


GMutex

typedef struct _GMutex GMutex;

The GMutex struct is an opaque data structure to represent a mutex (mutual exclusion). It can be used to protect data against shared access. Take for example the following function:

 

Example 2. A function which will not work in a threaded environment

1
2
3
4
5
6
7
8
9
10
11
12
int
give_me_next_number (void)
{
static int current_number = 0;

/* now do a very complicated calculation to calculate the new
* number, this might for example be a random number generator
*/
current_number = calc_next_number (current_number);

return current_number;
}


It is easy to see that this won't work in a multi-threaded application. There current_number must be protected against shared access. A first naive implementation would be:

 

Example 3. The wrong way to write a thread-safe function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int
give_me_next_number (void)
{
static int current_number = 0;
int ret_val;
static GMutex * mutex = NULL;

if (!mutex) mutex = g_mutex_new ();

g_mutex_lock (mutex);
ret_val = current_number = calc_next_number (current_number);
g_mutex_unlock (mutex);

return ret_val;
}


This looks like it would work, but there is a race condition while constructing the mutex and this code cannot work reliable. Please do not use such constructs in your own programs! One working solution is:

 

Example 4. A correct thread-safe function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
static GMutex *give_me_next_number_mutex = NULL;

/* this function must be called before any call to
* give_me_next_number()
*
* it must be called exactly once.
*/
void
init_give_me_next_number (void)
{
g_assert (give_me_next_number_mutex == NULL);
give_me_next_number_mutex = g_mutex_new ();
}

int
give_me_next_number (void)
{
static int current_number = 0;
int ret_val;

g_mutex_lock (give_me_next_number_mutex);
ret_val = current_number = calc_next_number (current_number);
g_mutex_unlock (give_me_next_number_mutex);

return ret_val;
}


GStaticMutex provides a simpler and safer way of doing this.

If you want to use a mutex, and your code should also work without calling g_thread_init() first, then you can not use a GMutex, as g_mutex_new() requires that the thread system be initialized. Use a GStaticMutex instead.

A GMutex should only be accessed via the following functions.

 

Note

All of the g_mutex_* functions are actually macros. Apart from taking their addresses, you can however use them as if they were functions.

 


g_mutex_new ()

GMutex *            g_mutex_new                         ();

Creates a new GMutex.

 

Note

This function will abort if g_thread_init() has not been called yet.

 

Returns :

a new GMutex.

g_mutex_lock ()

void                g_mutex_lock                        (GMutex *mutex);

Locks mutex. If mutex is already locked by another thread, the current thread will block until mutex is unlocked by the other thread.

This function can be used even if g_thread_init() has not yet been called, and, in that case, will do nothing.

 

Note

GMutex is neither guaranteed to be recursive nor to be non-recursive, i.e. a thread could deadlock while calling g_mutex_lock(), if it already has locked mutex. Use GStaticRecMutex, if you need recursive mutexes.

 

mutex :

a GMutex.

g_mutex_trylock ()

gboolean            g_mutex_trylock                     (GMutex *mutex);

Tries to lock mutex. If mutex is already locked by another thread, it immediately returns FALSE. Otherwise it locks mutex and returns TRUE.

This function can be used even if g_thread_init() has not yet been called, and, in that case, will immediately return TRUE.

 

Note

GMutex is neither guaranteed to be recursive nor to be non-recursive, i.e. the return value of g_mutex_trylock() could be both FALSE or TRUE, if the current thread already has locked mutex. Use GStaticRecMutex, if you need recursive mutexes.

 

mutex :

a GMutex.

Returns :

TRUE, if mutex could be locked.

g_mutex_unlock ()

void                g_mutex_unlock                      (GMutex *mutex);

Unlocks mutex. If another thread is blocked in a g_mutex_lock() call for mutex, it will be woken and can lock mutex itself.

This function can be used even if g_thread_init() has not yet been called, and, in that case, will do nothing.

mutex :

a GMutex.

g_mutex_free ()

void                g_mutex_free                        (GMutex *mutex);

Destroys mutex.

 

Note

Calling g_mutex_free() on a locked mutex may result in undefined behaviour.

 

mutex :

a GMutex.

GStaticMutex

typedef struct _GStaticMutex GStaticMutex;

A GStaticMutex works like a GMutex, but it has one significant advantage. It doesn't need to be created at run-time like a GMutex, but can be defined at compile-time. Here is a shorter, easier and safer version of our give_me_next_number() example:

 

Example 5.  Using GStaticMutex to simplify thread-safe programming

1
2
3
4
5
6
7
8
9
10
11
12
13
int
give_me_next_number (void)
{
static int current_number = 0;
int ret_val;
static GStaticMutex mutex = G_STATIC_MUTEX_INIT;

g_static_mutex_lock (&mutex);
ret_val = current_number = calc_next_number (current_number);
g_static_mutex_unlock (&mutex);

return ret_val;
}


Sometimes you would like to dynamically create a mutex. If you don't want to require prior calling to g_thread_init(), because your code should also be usable in non-threaded programs, you are not able to use g_mutex_new() and thus GMutex, as that requires a prior call to g_thread_init(). In theses cases you can also use a GStaticMutex. It must be initialized with g_static_mutex_init() before using it and freed with with g_static_mutex_free() when not needed anymore to free up any allocated resources.

Even though GStaticMutex is not opaque, it should only be used with the following functions, as it is defined differently on different platforms.

All of the g_static_mutex_* functions apart from g_static_mutex_get_mutex can also be used even if g_thread_init() has not yet been called. Then they do nothing, apart from g_static_mutex_trylock, which does nothing but returning TRUE.

 

Note

All of the g_static_mutex_* functions are actually macros. Apart from taking their addresses, you can however use them as if they were functions.

 


G_STATIC_MUTEX_INIT

#define G_STATIC_MUTEX_INIT

A GStaticMutex must be initialized with this macro, before it can be used. This macro can used be to initialize a variable, but it cannot be assigned to a variable. In that case you have to use g_static_mutex_init().

 

 


g_static_mutex_init ()

void                g_static_mutex_init                 (GStaticMutex *mutex);

Initializes mutex. Alternatively you can initialize it with G_STATIC_MUTEX_INIT.

mutex :

a GStaticMutex to be initialized.

g_static_mutex_lock ()

void                g_static_mutex_lock                 (GStaticMutex *mutex);

Works like g_mutex_lock(), but for a GStaticMutex.

mutex :

a GStaticMutex.

g_static_mutex_trylock ()

gboolean            g_static_mutex_trylock              (GStaticMutex *mutex);

Works like g_mutex_trylock(), but for a GStaticMutex.

mutex :

a GStaticMutex.

Returns :

TRUE, if the GStaticMutex could be locked.

g_static_mutex_unlock ()

void                g_static_mutex_unlock               (GStaticMutex *mutex);

Works like g_mutex_unlock(), but for a GStaticMutex.

mutex :

a GStaticMutex.

g_static_mutex_get_mutex ()

GMutex *            g_static_mutex_get_mutex            (GStaticMutex *mutex);

For some operations (like g_cond_wait()) you must have a GMutex instead of a GStaticMutex. This function will return the corresponding GMutex for mutex.

mutex :

a GStaticMutex.

Returns :

the GMutex corresponding to mutex.

g_static_mutex_free ()

void                g_static_mutex_free                 (GStaticMutex *mutex);

Releases all resources allocated to mutex.

You don't have to call this functions for a GStaticMutex with an unbounded lifetime, i.e. objects declared 'static', but if you have a GStaticMutex as a member of a structure and the structure is freed, you should also free the GStaticMutex.

 

Note

Calling g_static_mutex_free() on a locked mutex may result in undefined behaviour.

 

mutex :

a GStaticMutex to be freed.

G_LOCK_DEFINE()

#define             G_LOCK_DEFINE(name)

The G_LOCK_* macros provide a convenient interface to GStaticMutex with the advantage that they will expand to nothing in programs compiled against a thread-disabled GLib, saving code and memory there. G_LOCK_DEFINE defines a lock. It can appear anywhere variable definitions may appear in programs, i.e. in the first block of a function or outside of functions. The name parameter will be mangled to get the name of the GStaticMutex. This means that you can use names of existing variables as the parameter - e.g. the name of the variable you intent to protect with the lock. Look at our give_me_next_number() example using the G_LOCK_* macros:

 

Example 6. Using the G_LOCK_* convenience macros

1
2
3
4
5
6
7
8
9
10
11
12
13
14
G_LOCK_DEFINE (current_number);

int
give_me_next_number (void)
{
static int current_number = 0;
int ret_val;

G_LOCK (current_number);
ret_val = current_number = calc_next_number (current_number);
G_UNLOCK (current_number);

return ret_val;
}


name :

the name of the lock.

G_LOCK_DEFINE_STATIC()

#define             G_LOCK_DEFINE_STATIC(name)

This works like G_LOCK_DEFINE, but it creates a static object.

name :

the name of the lock.

G_LOCK_EXTERN()

#define             G_LOCK_EXTERN(name)

This declares a lock, that is defined with G_LOCK_DEFINE in another module.

name :

the name of the lock.

G_LOCK()

#define             G_LOCK(name)

Works like g_mutex_lock(), but for a lock defined with G_LOCK_DEFINE.

name :

the name of the lock.

G_TRYLOCK()

#define             G_TRYLOCK(name)

Works like g_mutex_trylock(), but for a lock defined with G_LOCK_DEFINE.

name :

the name of the lock.

Returns :

TRUE, if the lock could be locked.

G_UNLOCK()

#define             G_UNLOCK(name)

Works like g_mutex_unlock(), but for a lock defined with G_LOCK_DEFINE.

name :

the name of the lock.

GStaticRecMutex

typedef struct {
} GStaticRecMutex;

A GStaticRecMutex works like a GStaticMutex, but it can be locked multiple times by one thread. If you enter it n times, you have to unlock it n times again to let other threads lock it. An exception is the function g_static_rec_mutex_unlock_full(): that allows you to unlock a GStaticRecMutex completely returning the depth, (i.e. the number of times this mutex was locked). The depth can later be used to restore the state of the GStaticRecMutex by calling g_static_rec_mutex_lock_full().

Even though GStaticRecMutex is not opaque, it should only be used with the following functions.

All of the g_static_rec_mutex_* functions can be used even if g_thread_init() has not been called. Then they do nothing, apart from g_static_rec_mutex_trylock, which does nothing but returning TRUE.


G_STATIC_REC_MUTEX_INIT

#define G_STATIC_REC_MUTEX_INIT { G_STATIC_MUTEX_INIT }

A GStaticRecMutex must be initialized with this macro before it can be used. This macro can used be to initialize a variable, but it cannot be assigned to a variable. In that case you have to use g_static_rec_mutex_init().

 

 


g_static_rec_mutex_init ()

void                g_static_rec_mutex_init             (GStaticRecMutex *mutex);

A GStaticRecMutex must be initialized with this function before it can be used. Alternatively you can initialize it with G_STATIC_REC_MUTEX_INIT.

mutex :

a GStaticRecMutex to be initialized.

g_static_rec_mutex_lock ()

void                g_static_rec_mutex_lock             (GStaticRecMutex *mutex);

Locks mutex. If mutex is already locked by another thread, the current thread will block until mutex is unlocked by the other thread. If mutex is already locked by the calling thread, this functions increases the depth of mutex and returns immediately.

mutex :

a GStaticRecMutex to lock.

g_static_rec_mutex_trylock ()

gboolean            g_static_rec_mutex_trylock          (GStaticRecMutex *mutex);

Tries to lock mutex. If mutex is already locked by another thread, it immediately returns FALSE. Otherwise it locks mutex and returns TRUE. If mutex is already locked by the calling thread, this functions increases the depth of mutex and immediately returns TRUE.

mutex :

a GStaticRecMutex to lock.

Returns :

TRUE, if mutex could be locked.

g_static_rec_mutex_unlock ()

void                g_static_rec_mutex_unlock           (GStaticRecMutex *mutex);

Unlocks mutex. Another thread will be allowed to lock mutex only when it has been unlocked as many times as it had been locked before. If mutex is completely unlocked and another thread is blocked in a g_static_rec_mutex_lock() call for mutex, it will be woken and can lock mutex itself.

mutex :

a GStaticRecMutex to unlock.

g_static_rec_mutex_lock_full ()

void                g_static_rec_mutex_lock_full        (GStaticRecMutex *mutex,
guint depth);

Works like calling g_static_rec_mutex_lock() for mutex depth times.

mutex :

a GStaticRecMutex to lock.

depth :

number of times this mutex has to be unlocked to be completely unlocked.

g_static_rec_mutex_unlock_full ()

guint               g_static_rec_mutex_unlock_full      (GStaticRecMutex *mutex);

Completely unlocks mutex. If another thread is blocked in a g_static_rec_mutex_lock() call for mutex, it will be woken and can lock mutex itself. This function returns the number of times that mutex has been locked by the current thread. To restore the state before the call to g_static_rec_mutex_unlock_full() you can call g_static_rec_mutex_lock_full() with the depth returned by this function.

mutex :

a GStaticRecMutex to completely unlock.

Returns :

number of times mutex has been locked by the current thread.

g_static_rec_mutex_free ()

void                g_static_rec_mutex_free             (GStaticRecMutex *mutex);

Releases all resources allocated to a GStaticRecMutex.

You don't have to call this functions for a GStaticRecMutex with an unbounded lifetime, i.e. objects declared 'static', but if you have a GStaticRecMutex as a member of a structure and the structure is freed, you should also free the GStaticRecMutex.

mutex :

a GStaticRecMutex to be freed.

GStaticRWLock

typedef struct {
} GStaticRWLock;

The GStaticRWLock struct represents a read-write lock. A read-write lock can be used for protecting data that some portions of code only read from, while others also write. In such situations it is desirable that several readers can read at once, whereas of course only one writer may write at a time. Take a look at the following example:

 

Example 7. An array with access functions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
GStaticRWLock rwlock = G_STATIC_RW_LOCK_INIT;
GPtrArray *array;

gpointer
my_array_get (guint index)
{
gpointer retval = NULL;

if (!array)
return NULL;

g_static_rw_lock_reader_lock (&rwlock);
if (index < array->len)
retval = g_ptr_array_index (array, index);
g_static_rw_lock_reader_unlock (&rwlock);

return retval;
}

void
my_array_set (guint index, gpointer data)
{
g_static_rw_lock_writer_lock (&rwlock);

if (!array)
array = g_ptr_array_new ();

if (index >= array->len)
g_ptr_array_set_size (array, index+1);
g_ptr_array_index (array, index) = data;

g_static_rw_lock_writer_unlock (&rwlock);
}


This example shows an array which can be accessed by many readers (the my_array_get() function) simultaneously, whereas the writers (the my_array_set() function) will only be allowed once at a time and only if no readers currently access the array. This is because of the potentially dangerous resizing of the array. Using these functions is fully multi-thread safe now.

Most of the time, writers should have precedence over readers. That means, for this implementation, that as soon as a writer wants to lock the data, no other reader is allowed to lock the data, whereas, of course, the readers that already have locked the data are allowed to finish their operation. As soon as the last reader unlocks the data, the writer will lock it.

Even though GStaticRWLock is not opaque, it should only be used with the following functions.

All of the g_static_rw_lock_* functions can be used even if g_thread_init() has not been called. Then they do nothing, apart from g_static_rw_lock_*_trylock, which does nothing but returning TRUE.

 

Note

A read-write lock has a higher overhead than a mutex. For example, both g_static_rw_lock_reader_lock() and g_static_rw_lock_reader_unlock() have to lock and unlock a GStaticMutex, so it takes at least twice the time to lock and unlock a GStaticRWLock that it does to lock and unlock a GStaticMutex. So only data structures that are accessed by multiple readers, and which keep the lock for a considerable time justify a GStaticRWLock. The above example most probably would fare better with a GStaticMutex.

 


G_STATIC_RW_LOCK_INIT

#define G_STATIC_RW_LOCK_INIT { G_STATIC_MUTEX_INIT, NULL, NULL, 0, FALSE, 0, 0 }

A GStaticRWLock must be initialized with this macro before it can be used. This macro can used be to initialize a variable, but it cannot be assigned to a variable. In that case you have to use g_static_rw_lock_init().

 

 


g_static_rw_lock_init ()

void                g_static_rw_lock_init               (GStaticRWLock *lock);

A GStaticRWLock must be initialized with this function before it can be used. Alternatively you can initialize it with G_STATIC_RW_LOCK_INIT.

lock :

a GStaticRWLock to be initialized.

g_static_rw_lock_reader_lock ()

void                g_static_rw_lock_reader_lock        (GStaticRWLock *lock);

Locks lock for reading. There may be unlimited concurrent locks for reading of a GStaticRWLock at the same time. If lock is already locked for writing by another thread or if another thread is already waiting to lock lock for writing, this function will block until lock is unlocked by the other writing thread and no other writing threads want to lock lock. This lock has to be unlocked by g_static_rw_lock_reader_unlock().

GStaticRWLock is not recursive. It might seem to be possible to recursively lock for reading, but that can result in a deadlock, due to writer preference.

lock :

a GStaticRWLock to lock for reading.

g_static_rw_lock_reader_trylock ()

gboolean            g_static_rw_lock_reader_trylock     (GStaticRWLock *lock);

Tries to lock lock for reading. If lock is already locked for writing by another thread or if another thread is already waiting to lock lock for writing, immediately returns FALSE. Otherwise locks lock for reading and returns TRUE. This lock has to be unlocked by g_static_rw_lock_reader_unlock().

lock :

a GStaticRWLock to lock for reading.

Returns :

TRUE, if lock could be locked for reading.

g_static_rw_lock_reader_unlock ()

void                g_static_rw_lock_reader_unlock      (GStaticRWLock *lock);

Unlocks lock. If a thread waits to lock lock for writing and all locks for reading have been unlocked, the waiting thread is woken up and can lock lock for writing.

lock :

a GStaticRWLock to unlock after reading.

g_static_rw_lock_writer_lock ()

void                g_static_rw_lock_writer_lock        (GStaticRWLock *lock);

Locks lock for writing. If lock is already locked for writing or reading by other threads, this function will block until lock is completely unlocked and then lock lock for writing. While this functions waits to lock lock, no other thread can lock lock for reading. When lock is locked for writing, no other thread can lock lock (neither for reading nor writing). This lock has to be unlocked by g_static_rw_lock_writer_unlock().

lock :

a GStaticRWLock to lock for writing.

g_static_rw_lock_writer_trylock ()

gboolean            g_static_rw_lock_writer_trylock     (GStaticRWLock *lock);

Tries to lock lock for writing. If lock is already locked (for either reading or writing) by another thread, it immediately returns FALSE. Otherwise it locks lock for writing and returns TRUE. This lock has to be unlocked by g_static_rw_lock_writer_unlock().

lock :

a GStaticRWLock to lock for writing.

Returns :

TRUE, if lock could be locked for writing.

g_static_rw_lock_writer_unlock ()

void                g_static_rw_lock_writer_unlock      (GStaticRWLock *lock);

Unlocks lock. If a thread is waiting to lock lock for writing and all locks for reading have been unlocked, the waiting thread is woken up and can lock lock for writing. If no thread is waiting to lock lock for writing, and some thread or threads are waiting to lock lock for reading, the waiting threads are woken up and can lock lock for reading.

lock :

a GStaticRWLock to unlock after writing.

g_static_rw_lock_free ()

void                g_static_rw_lock_free               (GStaticRWLock *lock);

Releases all resources allocated to lock.

You don't have to call this functions for a GStaticRWLock with an unbounded lifetime, i.e. objects declared 'static', but if you have a GStaticRWLock as a member of a structure, and the structure is freed, you should also free the GStaticRWLock.

lock :

a GStaticRWLock to be freed.

GCond

typedef struct _GCond GCond;

The GCond struct is an opaque data structure that represents a condition. Threads can block on a GCond if they find a certain condition to be false. If other threads change the state of this condition they signal the GCond, and that causes the waiting threads to be woken up.

 

Example 8.  Using GCond to block a thread until a condition is satisfied

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
GCond* data_cond = NULL; /* Must be initialized somewhere */
GMutex* data_mutex = NULL; /* Must be initialized somewhere */
gpointer current_data = NULL;

void
push_data (gpointer data)
{
g_mutex_lock (data_mutex);
current_data = data;
g_cond_signal (data_cond);
g_mutex_unlock (data_mutex);
}

gpointer
pop_data (void)
{
gpointer data;

g_mutex_lock (data_mutex);
while (!current_data)
g_cond_wait (data_cond, data_mutex);
data = current_data;
current_data = NULL;
g_mutex_unlock (data_mutex);

return data;
}


Whenever a thread calls pop_data() now, it will wait until current_data is non-NULL, i.e. until some other thread has called push_data().

 

Note

It is important to use the g_cond_wait() and g_cond_timed_wait() functions only inside a loop which checks for the condition to be true. It is not guaranteed that the waiting thread will find the condition fulfilled after it wakes up, even if the signaling thread left the condition in that state: another thread may have altered the condition before the waiting thread got the chance to be woken up, even if the condition itself is protected by a GMutex, like above.

 

A GCond should only be accessed via the following functions.

 

Note

All of the g_cond_* functions are actually macros. Apart from taking their addresses, you can however use them as if they were functions.

 


g_cond_new ()

GCond*              g_cond_new                          ();

Creates a new GCond. This function will abort, if g_thread_init() has not been called yet.

Returns :

a new GCond.

g_cond_signal ()

void                g_cond_signal                       (GCond *cond);

If threads are waiting for cond, exactly one of them is woken up. It is good practice to hold the same lock as the waiting thread while calling this function, though not required.

This function can be used even if g_thread_init() has not yet been called, and, in that case, will do nothing.

cond :

a GCond.

g_cond_broadcast ()

void                g_cond_broadcast                    (GCond *cond);

If threads are waiting for cond, all of them are woken up. It is good practice to lock the same mutex as the waiting threads, while calling this function, though not required.

This function can be used even if g_thread_init() has not yet been called, and, in that case, will do nothing.

cond :

a GCond.

g_cond_wait ()

void                g_cond_wait                         (GCond *cond,
GMutex *mutex);

Waits until this thread is woken up on cond. The mutex is unlocked before falling asleep and locked again before resuming.

This function can be used even if g_thread_init() has not yet been called, and, in that case, will immediately return.

cond :

a GCond.

mutex :

a GMutex, that is currently locked.

g_cond_timed_wait ()

gboolean            g_cond_timed_wait                   (GCond *cond,
GMutex *mutex,
GTimeVal *abs_time);

Waits until this thread is woken up on cond, but not longer than until the time specified by abs_time. The mutex is unlocked before falling asleep and locked again before resuming.

If abs_time is NULL, g_cond_timed_wait() acts like g_cond_wait().

This function can be used even if g_thread_init() has not yet been called, and, in that case, will immediately return TRUE.

To easily calculate abs_time a combination of g_get_current_time() and g_time_val_add() can be used.

cond :

a GCond.

mutex :

a GMutex that is currently locked.

abs_time :

a GTimeVal, determining the final time.

Returns :

TRUE if cond was signalled, or FALSE on timeout.

g_cond_free ()

void                g_cond_free                         (GCond *cond);

Destroys the GCond.

cond :

a GCond.

GPrivate

typedef struct _GPrivate GPrivate;

The GPrivate struct is an opaque data structure to represent a thread private data key. Threads can thereby obtain and set a pointer which is private to the current thread. Take our give_me_next_number() example from above. Suppose we don't want current_number to be shared between the threads, but instead to be private to each thread. This can be done as follows:

 

Example 9. Using GPrivate for per-thread data

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
GPrivate* current_number_key = NULL; /* Must be initialized somewhere
with g_private_new (g_free); */

int
give_me_next_number (void)
{
int *current_number = g_private_get (current_number_key);

if (!current_number)
{
current_number = g_new (int, 1);
*current_number = 0;
g_private_set (current_number_key, current_number);
}

*current_number = calc_next_number (*current_number);

return *current_number;
}


Here the pointer belonging to the key current_number_key is read. If it is NULL, it has not been set yet. Then get memory for an integer value, assign this memory to the pointer and write the pointer back. Now we have an integer value that is private to the current thread.

The GPrivate struct should only be accessed via the following functions.

 

Note

All of the g_private_* functions are actually macros. Apart from taking their addresses, you can however use them as if they were functions.

 


g_private_new ()

GPrivate*           g_private_new                       (GDestroyNotify destructor);

Creates a new GPrivate. If destructor is non-NULL, it is a pointer to a destructor function. Whenever a thread ends and the corresponding pointer keyed to this instance of GPrivate is non-NULL, the destructor is called with this pointer as the argument.

 

Note

destructor is used quite differently from notify in g_static_private_set().

 

 

Note

A GPrivate can not be freed. Reuse it instead, if you can, to avoid shortage, or use GStaticPrivate.

 

 

Note

This function will abort if g_thread_init() has not been called yet.

 

destructor :

a function to destroy the data keyed to GPrivate when a thread ends.

Returns :

a new GPrivate.

g_private_get ()

gpointer            g_private_get                       (GPrivate *private_key);

Returns the pointer keyed to private_key for the current thread. If g_private_set() hasn't been called for the current private_key and thread yet, this pointer will be NULL.

This function can be used even if g_thread_init() has not yet been called, and, in that case, will return the value of private_key casted to gpointer. Note however, that private data set before g_thread_init() will not be retained after the call. Instead, NULL will be returned in all threads directly after g_thread_init(), regardless of any g_private_set() calls issued before threading system intialization.

private_key :

a GPrivate.

Returns :

the corresponding pointer.

g_private_set ()

void                g_private_set                       (GPrivate *private_key,
gpointer data);

Sets the pointer keyed to private_key for the current thread.

This function can be used even if g_thread_init() has not yet been called, and, in that case, will set private_key to data casted to GPrivate*. See g_private_get() for resulting caveats.

private_key :

a GPrivate.

data :

the new pointer.

GStaticPrivate

typedef struct {
} GStaticPrivate;

A GStaticPrivate works almost like a GPrivate, but it has one significant advantage. It doesn't need to be created at run-time like a GPrivate, but can be defined at compile-time. This is similar to the difference between GMutex and GStaticMutex. Now look at our give_me_next_number() example with GStaticPrivate:

 

Example 10. Using GStaticPrivate for per-thread data

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int
give_me_next_number ()
{
static GStaticPrivate current_number_key = G_STATIC_PRIVATE_INIT;
int *current_number = g_static_private_get (&current_number_key);

if (!current_number)
{
current_number = g_new (int,1);
*current_number = 0;
g_static_private_set (&current_number_key, current_number, g_free);
}

*current_number = calc_next_number (*current_number);

return *current_number;
}



G_STATIC_PRIVATE_INIT

#define G_STATIC_PRIVATE_INIT 

Every GStaticPrivate must be initialized with this macro, before it can be used.

 

 


g_static_private_init ()

void                g_static_private_init               (GStaticPrivate *private_key);

Initializes private_key. Alternatively you can initialize it with G_STATIC_PRIVATE_INIT.

private_key :

a GStaticPrivate to be initialized.

g_static_private_get ()

gpointer            g_static_private_get                (GStaticPrivate *private_key);

Works like g_private_get() only for a GStaticPrivate.

This function works even if g_thread_init() has not yet been called.

private_key :

a GStaticPrivate.

Returns :

the corresponding pointer.

g_static_private_set ()

void                g_static_private_set                (GStaticPrivate *private_key,
gpointer data,
GDestroyNotify notify);

Sets the pointer keyed to private_key for the current thread and the function notify to be called with that pointer (NULL or non-NULL), whenever the pointer is set again or whenever the current thread ends.

This function works even if g_thread_init() has not yet been called. If g_thread_init() is called later, the data keyed to private_key will be inherited only by the main thread, i.e. the one that called g_thread_init().

 

Note

notify is used quite differently from destructor in g_private_new().

 

private_key :

a GStaticPrivate.

data :

the new pointer.

notify :

a function to be called with the pointer whenever the current thread ends or sets this pointer again.

g_static_private_free ()

void                g_static_private_free               (GStaticPrivate *private_key);

Releases all resources allocated to private_key.

You don't have to call this functions for a GStaticPrivate with an unbounded lifetime, i.e. objects declared 'static', but if you have a GStaticPrivate as a member of a structure and the structure is freed, you should also free the GStaticPrivate.

private_key :

a GStaticPrivate to be freed.

GOnce

typedef struct {
volatile GOnceStatus status;
volatile gpointer retval;
} GOnce;

A GOnce struct controls a one-time initialization function. Any one-time initialization function must have its own unique GOnce struct.

volatile GOnceStatus status;

the status of the GOnce

volatile gpointer retval;

the value returned by the call to the function, if status is G_ONCE_STATUS_READY

Since 2.4


enum GOnceStatus

typedef enum
{
G_ONCE_STATUS_NOTCALLED,
G_ONCE_STATUS_PROGRESS,
G_ONCE_STATUS_READY
} GOnceStatus;

The possible statuses of a one-time initialization function controlled by a GOnce struct.

G_ONCE_STATUS_NOTCALLED

the function has not been called yet.

G_ONCE_STATUS_PROGRESS

the function call is currently in progress.

G_ONCE_STATUS_READY

the function has been called.

Since 2.4


G_ONCE_INIT

#define G_ONCE_INIT { G_ONCE_STATUS_NOTCALLED, NULL }

A GOnce must be initialized with this macro before it can be used.

 

1
GOnce my_once = G_ONCE_INIT;

 

Since 2.4


g_once()

#define             g_once(once, func, arg)

The first call to this routine by a process with a given GOnce struct calls func with the given argument. Thereafter, subsequent calls to g_once() with the same GOnce struct do not call func again, but return the stored result of the first call. On return from g_once(), the status of once will be G_ONCE_STATUS_READY.

For example, a mutex or a thread-specific data key must be created exactly once. In a threaded environment, calling g_once() ensures that the initialization is serialized across multiple threads.

 

Note

Calling g_once() recursively on the same GOnce struct in func will lead to a deadlock.

 

 

1
2
3
4
5
6
7
8
9
gpointer
get_debug_flags (void)
{
static GOnce my_once = G_ONCE_INIT;

g_once (&my_once, parse_debug_flags, NULL);

return my_once.retval;
}

 

once :

a GOnce structure

func :

the GThreadFunc function associated to once. This function is called only once, regardless of the number of times it and its associated GOnce struct are passed to g_once().

arg :

data to be passed to func

Since 2.4


g_once_init_enter ()

gboolean            g_once_init_enter                   (volatile gsize *value_location);

Function to be called when starting a critical initialization section. The argument value_location must point to a static 0-initialized variable that will be set to a value other than 0 at the end of the initialization section. In combination with g_once_init_leave() and the unique address value_location, it can be ensured that an initialization section will be executed only once during a program's life time, and that concurrent threads are blocked until initialization completed. To be used in constructs like this:

 

1
2
3
4
5
6
7
8
9
10
static gsize initialization_value = 0;

if (g_once_init_enter (&initialization_value))
{
gsize setup_value = 42; /* initialization code here */

g_once_init_leave (&initialization_value, setup_value);
}

/* use initialization_value here */

 

value_location :

location of a static initializable variable containing 0.

Returns :

TRUE if the initialization section should be entered, FALSE and blocks otherwise

Since 2.14


g_once_init_leave ()

void                g_once_init_leave                   (volatile gsize *value_location,
gsize initialization_value);

Counterpart to g_once_init_enter(). Expects a location of a static 0-initialized initialization variable, and an initialization value other than 0. Sets the variable to the initialization value, and releases concurrent threads blocking in g_once_init_enter() on this initialization variable.

value_location :

location of a static initializable variable containing 0.

initialization_value :

new non-0 value for *value_location.

Since 2.14


g_bit_lock ()

void                g_bit_lock                          (volatile gint *address,
gint lock_bit);

Sets the indicated lock_bit in address. If the bit is already set, this call will block until g_bit_unlock() unsets the corresponding bit.

Attempting to lock on two different bits within the same integer is not supported and will very probably cause deadlocks.

The value of the bit that is set is (1u << bit). If bit is not between 0 and 31 then the result is undefined.

This function accesses address atomically. All other accesses to address must be atomic in order for this function to work reliably.

address :

a pointer to an integer

lock_bit :

a bit value between 0 and 31

Since 2.24


g_bit_trylock ()

gboolean            g_bit_trylock                       (volatile gint *address,
gint lock_bit);

Sets the indicated lock_bit in address, returning TRUE if successful. If the bit is already set, returns FALSE immediately.

Attempting to lock on two different bits within the same integer is not supported.

The value of the bit that is set is (1u << bit). If bit is not between 0 and 31 then the result is undefined.

This function accesses address atomically. All other accesses to address must be atomic in order for this function to work reliably.

address :

a pointer to an integer

lock_bit :

a bit value between 0 and 31

Returns :

TRUE if the lock was acquired

Since 2.24


g_bit_unlock ()

void                g_bit_unlock                        (volatile gint *address,
gint lock_bit);

Clears the indicated lock_bit in address. If another thread is currently blocked in g_bit_lock() on this same bit then it will be woken up.

This function accesses address atomically. All other accesses to address must be atomic in order for this function to work reliably.

address :

a pointer to an integer

lock_bit :

a bit value between 0 and 31

Since 2.24

訊息輸出跟除錯函式

Message Output and Debugging Functions — functions to output messages and help debug applications

 

Synopsis

#include <glib.h>

void g_print (const gchar *format,
...);
GPrintFunc g_set_print_handler (GPrintFunc func);
void (*GPrintFunc) (const gchar *string);

void g_printerr (const gchar *format,
...);
GPrintFunc g_set_printerr_handler (GPrintFunc func);

#define g_return_if_fail (expr)
#define g_return_val_if_fail (expr,
val)
#define g_return_if_reached
#define g_return_val_if_reached (val)
#define g_warn_if_fail (expr)
#define g_warn_if_reached

void g_on_error_query (const gchar *prg_name);
void g_on_error_stack_trace (const gchar *prg_name);

#define G_BREAKPOINT

Description

These functions provide support for outputting messages.

The g_return family of macros (g_return_if_fail(), g_return_val_if_fail(), g_return_if_reached(), g_return_val_if_reached()) should only be used for programming errors, a typical use case is checking for invalid parameters at the beginning of a public function. They should not be used if you just mean "if (error) return", they should only be used if you mean "if (bug in program) return". The program behavior is generally considered undefined after one of these checks fails. They are not intended for normal control flow, only to give a perhaps-helpful warning before giving up.

Details

g_print ()

void                g_print                             (const gchar *format,
...);

Outputs a formatted message via the print handler. The default print handler simply outputs the message to stdout.

g_print() should not be used from within libraries for debugging messages, since it may be redirected by applications to special purpose message windows or even files. Instead, libraries should use g_log(), or the convenience functions g_message(), g_warning() and g_error().

format :

the message format. See the printf() documentation.

... :

the parameters to insert into the format string.

g_set_print_handler ()

GPrintFunc          g_set_print_handler                 (GPrintFunc func);

設定列印處理器,任何傳到g_print() 的訊息會透過這個新的處理器輸出,預設的處理器簡單地輸出訊息到stdout,你可以提供自己的處理器來將輸出轉向,例如轉到一個GTK+元件或一個紀錄檔。

func :

新的列印處理器。

傳回:

舊的列印處理器。

GPrintFunc ()

void                (*GPrintFunc)                       (const gchar *string);

Specifies the type of the print handler functions. These are called with the complete formatted string to output.

string :

the message to be output.

g_printerr ()

void                g_printerr                          (const gchar *format,
...);

Outputs a formatted message via the error message handler. The default handler simply outputs the message to stderr.

g_printerr() should not be used from within libraries. Instead g_log() should be used, or the convenience functions g_message(), g_warning() and g_error().

format :

the message format. See the printf() documentation.

... :

the parameters to insert into the format string.

g_set_printerr_handler ()

GPrintFunc          g_set_printerr_handler              (GPrintFunc func);

Sets the handler for printing error messages. Any messages passed to g_printerr() will be output via the new handler. The default handler simply outputs the message to stderr. By providing your own handler you can redirect the output, to a GTK+ widget or a log file for example.

func :

the new error message handler.

Returns :

the old error message handler.

g_return_if_fail()

#define             g_return_if_fail(expr)

Returns from the current function if the expression is not true. If the expression evaluates to FALSE, a critical message is logged and the function returns. This can only be used in functions which do not return a value.

expr :

the expression to check.

g_return_val_if_fail()

#define             g_return_val_if_fail(expr,val)

Returns from the current function, returning the value val, if the expression is not true. If the expression evaluates to FALSE, a critical message is logged and val is returned.

expr :

the expression to check.

val :

the value to return from the current function if the expression is not true.

g_return_if_reached

#define             g_return_if_reached()

Logs a critical message and returns from the current function. This can only be used in functions which do not return a value.


g_return_val_if_reached()

#define             g_return_val_if_reached(val)

Logs a critical message and returns val.

val :

the value to return from the current function.

g_warn_if_fail()

#define             g_warn_if_fail(expr)

Logs a warning if the expression is not true.

expr :

the expression to check

Since 2.16


g_warn_if_reached

#define             g_warn_if_reached()

Logs a critical warning.

Since 2.16


g_on_error_query ()

void                g_on_error_query                    (const gchar *prg_name);

Prompts the user with [E]xit, [H]alt, show [S]tack trace or [P]roceed. This function is intended to be used for debugging use only. The following example shows how it can be used together with the g_log() functions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <glib.h>
static void
log_handler (const gchar *log_domain,
GLogLevelFlags log_level,
const gchar *message,
gpointer user_data)
{
g_log_default_handler (log_domain, log_level, message, user_data);
g_on_error_query (MY_PROGRAM_NAME);
}
int main (int argc, char *argv[])
{
g_log_set_handler (MY_LOG_DOMAIN,
G_LOG_LEVEL_WARNING |
G_LOG_LEVEL_ERROR |
G_LOG_LEVEL_CRITICAL,
log_handler,
NULL);
/* ... */

If [E]xit is selected, the application terminates with a call to _exit(0).

If [H]alt is selected, the application enters an infinite loop. The infinite loop can only be stopped by killing the application, or by setting glib_on_error_halt to FALSE (possibly via a debugger).

If [S]tack trace is selected, g_on_error_stack_trace() is called. This invokes gdb, which attaches to the current process and shows a stack trace. The prompt is then shown again.

If [P]roceed is selected, the function returns.

This function may cause different actions on non-UNIX platforms.

prg_name :

the program name, needed by gdb for the [S]tack trace option. If prg_name is NULL, g_get_prgname() is called to get the program name (which will work correctly if gdk_init() or gtk_init() has been called).

g_on_error_stack_trace ()

void                g_on_error_stack_trace              (const gchar *prg_name);

Invokes gdb, which attaches to the current process and shows a stack trace. Called by g_on_error_query() when the [S]tack trace option is selected.

This function may cause different actions on non-UNIX platforms.

prg_name :

the program name, needed by gdb for the [S]tack trace option. If prg_name is NULL, g_get_prgname() is called to get the program name (which will work correctly if gdk_init() or gtk_init() has been called).

G_BREAKPOINT

#define             G_BREAKPOINT()

Inserts a breakpoint instruction into the code. On x86 and alpha systems this is implemented as a soft interrupt and on other architectures it raises a SIGTRAP signal.

訊息紀錄

Message Logging — versatile support for logging messages with different levels of importance

 

Synopsis

#include <glib.h>

#define G_LOG_DOMAIN
#define G_LOG_FATAL_MASK
#define G_LOG_LEVEL_USER_SHIFT
void (*GLogFunc) (const gchar *log_domain,
GLogLevelFlags log_level,
const gchar *message,
gpointer user_data);
enum GLogLevelFlags;

void g_log (const gchar *log_domain,
GLogLevelFlags log_level,
const gchar *format,
...);
void g_logv (const gchar *log_domain,
GLogLevelFlags log_level,
const gchar *format,
va_list args);
#define g_message (...)
#define g_warning (...)
#define g_critical (...)
#define g_error (...)
#define g_debug (...)

guint g_log_set_handler (const gchar *log_domain,
GLogLevelFlags log_levels,
GLogFunc log_func,
gpointer user_data);
void g_log_remove_handler (const gchar *log_domain,
guint handler_id);
GLogLevelFlags g_log_set_always_fatal (GLogLevelFlags fatal_mask);
GLogLevelFlags g_log_set_fatal_mask (const gchar *log_domain,
GLogLevelFlags fatal_mask);
void g_log_default_handler (const gchar *log_domain,
GLogLevelFlags log_level,
const gchar *message,
gpointer unused_data);
GLogFunc g_log_set_default_handler (GLogFunc log_func,
gpointer user_data);

Description

These functions provide support for logging error messages or messages used for debugging.

There are several built-in levels of messages, defined in GLogLevelFlags. These can be extended with user-defined levels.

Details

G_LOG_DOMAIN

#define G_LOG_DOMAIN    ((gchar*) 0)

Defines the log domain. For applications, this is typically left as the default NULL (or "") domain. Libraries should define this so that any messages which they log can be differentiated from messages from other libraries and application code. But be careful not to define it in any public header files.

For example, GTK+ uses this in its Makefile.am:

INCLUDES = -DG_LOG_DOMAIN=\"Gtk\"

G_LOG_FATAL_MASK

#define G_LOG_FATAL_MASK        (G_LOG_FLAG_RECURSION | G_LOG_LEVEL_ERROR)

GLib log levels that are considered fatal by default.


G_LOG_LEVEL_USER_SHIFT

#define G_LOG_LEVEL_USER_SHIFT  (8)

Log level shift offset for user defined log levels (0-7 are used by GLib).


GLogFunc ()

void                (*GLogFunc)                         (const gchar *log_domain,
GLogLevelFlags log_level,
const gchar *message,
gpointer user_data);

Specifies the prototype of log handler functions.

log_domain :

the log domain of the message.

log_level :

the log level of the message (including the fatal and recursion flags).

message :

the message to process.

user_data :

user data, set in g_log_set_handler().

enum GLogLevelFlags

typedef enum
{
/* log flags */
G_LOG_FLAG_RECURSION = 1 << 0,
G_LOG_FLAG_FATAL = 1 << 1,

/* GLib log levels */
G_LOG_LEVEL_ERROR = 1 << 2, /* always fatal */
G_LOG_LEVEL_CRITICAL = 1 << 3,
G_LOG_LEVEL_WARNING = 1 << 4,
G_LOG_LEVEL_MESSAGE = 1 << 5,
G_LOG_LEVEL_INFO = 1 << 6,
G_LOG_LEVEL_DEBUG = 1 << 7,

G_LOG_LEVEL_MASK = ~(G_LOG_FLAG_RECURSION | G_LOG_FLAG_FATAL)
} GLogLevelFlags;

Flags specifying the level of log messages. It is possible to change how GLib treats messages of the various levels using g_log_set_handler() and g_log_set_fatal_mask().

G_LOG_FLAG_RECURSION

internal flag

G_LOG_FLAG_FATAL

internal flag

G_LOG_LEVEL_ERROR

log level for errors, see g_error(). This level is also used for messages produced by g_assert().

G_LOG_LEVEL_CRITICAL

log level for critical messages, see g_critical(). This level is also used for messages produced by g_return_if_fail() and g_return_val_if_fail().

G_LOG_LEVEL_WARNING

log level for warnings, see g_warning()

G_LOG_LEVEL_MESSAGE

log level for messages, see g_message()

G_LOG_LEVEL_INFO

log level for informational messages

G_LOG_LEVEL_DEBUG

log level for debug messages, see g_debug()

G_LOG_LEVEL_MASK

a mask including all log levels.

g_log ()

void                g_log                               (const gchar *log_domain,
GLogLevelFlags log_level,
const gchar *format,
...);

Logs an error or debugging message. If the log level has been set as fatal, the abort() function is called to terminate the program.

log_domain :

the log domain, usually G_LOG_DOMAIN.

log_level :

the log level, either from GLogLevelFlags or a user-defined level.

format :

the message format. See the printf() documentation.

... :

the parameters to insert into the format string.

g_logv ()

void                g_logv                              (const gchar *log_domain,
GLogLevelFlags log_level,
const gchar *format,
va_list args);

Logs an error or debugging message. If the log level has been set as fatal, the abort() function is called to terminate the program.

log_domain :

the log domain.

log_level :

the log level.

format :

the message format. See the printf() documentation.

args :

the parameters to insert into the format string.

g_message()

#define             g_message(...)

A convenience function/macro to log a normal message.

... :

format string, followed by parameters to insert into the format string (as with printf())

g_warning()

#define             g_warning(...)

一個方便的函式/巨集用來顯示警告訊息。

你可以在執行期藉著設定G_DEBUG環境變數(見Running GLib Applications)來產生警告致命的錯誤。

... :

格式字串,後面接著是參數插入格式字串中(就像printf())

g_critical()

#define             g_critical(...)

Logs a "critical warning" (G_LOG_LEVEL_CRITICAL). It's more or less application-defined what constitutes a critical vs. a regular warning. You could call g_log_set_always_fatal() to make critical warnings exit the program, then use g_critical() for fatal errors, for example.

You can also make critical warnings fatal at runtime by setting the G_DEBUG environment variable (see Running GLib Applications).

... :

format string, followed by parameters to insert into the format string (as with printf())

g_error()

#define             g_error(...)

A convenience function/macro to log an error message. Error messages are always fatal, resulting in a call to abort() to terminate the application. This function will result in a core dump; don't use it for errors you expect. Using this function indicates a bug in your program, i.e. an assertion failure.

... :

format string, followed by parameters to insert into the format string (as with printf())

g_debug()

#define             g_debug(...)

A convenience function/macro to log a debug message.

... :

format string, followed by parameters to insert into the format string (as with printf())

Since 2.6


g_log_set_handler ()

guint               g_log_set_handler                   (const gchar *log_domain,
GLogLevelFlags log_levels,
GLogFunc log_func,
gpointer user_data);

設定一個範圍的紀錄處理器以及紀錄層級,要處理致命的跟遞迴的訊息log_levels 參數必須跟G_LOG_FLAG_FATAL G_LOG_FLAG_RECURSION 位元旗標配合使用。

注意因為 G_LOG_LEVEL_ERROR 紀錄層級總是致命的,假如你想要設定這個紀錄層級的處理器,你必須結合 G_LOG_FLAG_FATAL使用。

範例12:在預設的(應用)範圍新增一個所有警告訊息的紀錄處理器

  g_log_set_handler (NULL, G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
| G_LOG_FLAG_RECURSION, my_log_handler, NULL);

範例13x:從GTK+新增一個重要訊息的紀錄處理器

  g_log_set_handler ("Gtk", G_LOG_LEVEL_CRITICAL | G_LOG_FLAG_FATAL
| G_LOG_FLAG_RECURSION, my_log_handler, NULL);

範例14:從GLib新增一個所有訊息的紀錄處理器

  g_log_set_handler ("GLib", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
| G_LOG_FLAG_RECURSION, my_log_handler, NULL);

log_domain :

紀錄範圍,或使用預設的 NULL 應用範圍。

log_levels :

紀錄處理器應用的紀錄層級,要處理致命的跟遞迴的續息,結合 G_LOG_FLAG_FATALG_LOG_FLAG_RECURSION 位元旗標的紀錄層級使用。

log_func :

紀錄處理器函式。

user_data :

傳到紀錄處理器的資料。

傳回:

新的處理器id。

g_log_remove_handler ()

void                g_log_remove_handler                (const gchar *log_domain,
guint handler_id);

Removes the log handler.

log_domain :

the log domain.

handler_id :

the id of the handler, which was returned in g_log_set_handler().

g_log_set_always_fatal ()

GLogLevelFlags      g_log_set_always_fatal              (GLogLevelFlags fatal_mask);

Sets the message levels which are always fatal, in any log domain. When a message with any of these levels is logged the program terminates. You can only set the levels defined by GLib to be fatal. G_LOG_LEVEL_ERROR is always fatal.

You can also make some message levels fatal at runtime by setting the G_DEBUG environment variable (see Running GLib Applications).

fatal_mask :

the mask containing bits set for each level of error which is to be fatal.

Returns :

the old fatal mask.

g_log_set_fatal_mask ()

GLogLevelFlags      g_log_set_fatal_mask                (const gchar *log_domain,
GLogLevelFlags fatal_mask);

Sets the log levels which are fatal in the given domain. G_LOG_LEVEL_ERROR is always fatal.

log_domain :

the log domain.

fatal_mask :

the new fatal mask.

Returns :

the old fatal mask for the log domain.

g_log_default_handler ()

void                g_log_default_handler               (const gchar *log_domain,
GLogLevelFlags log_level,
const gchar *message,
gpointer unused_data);

The default log handler set up by GLib; g_log_set_default_handler() allows to install an alternate default log handler. This is used if no log handler has been set for the particular log domain and log level combination. It outputs the message to stderr or stdout and if the log level is fatal it calls abort().

stderr is used for levels G_LOG_LEVEL_ERROR, G_LOG_LEVEL_CRITICAL, G_LOG_LEVEL_WARNING and G_LOG_LEVEL_MESSAGE. stdout is used for the rest.

log_domain :

the log domain of the message.

log_level :

the level of the message.

message :

the message.

unused_data :

data passed from g_log() which is unused.

g_log_set_default_handler ()

GLogFunc            g_log_set_default_handler           (GLogFunc log_func,
gpointer user_data);

Installs a default log handler which is used if no log handler has been set for the particular log domain and log level combination. By default, GLib uses g_log_default_handler() as default log handler.

log_func :

the log handler function.

user_data :

data passed to the log handler.

Returns :

the previous default log handler

Since 2.6

GLib實用函式集

String Utility Functions — 各種字串相關的函式
Character Set Conversion — 使用iconv()處理不同字元集間的轉換
Unicode操作(Unicode Manipulation) — 操作Unicode和UTF-8字串的函式
Base64 Encoding — Base64格式的編碼及解碼資料
Data Checksums — 計算資料的校驗和
國際化 — gettext 支援的巨集
日期和時間函式 — 曆法的計算及其他時間的雜項
Random Numbers虛擬亂數產生器
Hook Functions — 支援hook函式的操作列表
雜項實用功能 — 可移植的實用函式選擇
字典掃瞄器(Lexical Scanner)通用詞彙掃描儀
Automatic String Completion — 實用一組目標字串的自動完成支援
Timers — 追踪所用的時間
Spawning Processes —進程的啟動
File Utilities — 各種檔案相關的函式
URI 函式 — URI函式
主機名稱功能 — Internet主機名稱功能
Shell-related Utilities — shell-like命令列處理
命令行選項解析器 — 解析命令行選項
Glob-style pattern matching — 比對含有'*'(萬用字元)跟'?'樣式的字串
Perl-compatible regular expressions — 比對正規表示式的字串
Simple XML Subset Parser解析xml的一個子集
Key-value file parser — 解析.ini-之類的組態檔案
Bookmark file parser — 解析含有書籤的檔案
Testing — 一個測試架構
Windows Compatibility Functions — Windows上的UNIX模擬

雜項實用函式

雜項實用函式

雜項實用函式 — a selection of portable utility functions

 

一覽表

#include <glib.h>

const gchar* g_get_application_name (void);
void g_set_application_name (const gchar *application_name);
gchar* g_get_prgname (void);
void g_set_prgname (const gchar *prgname);
const gchar* g_getenv (const gchar *variable);
gboolean g_setenv (const gchar *variable,
const gchar *value,
gboolean overwrite);
void g_unsetenv (const gchar *variable);
gchar** g_listenv (void);
const gchar* g_get_user_name (void);
const gchar* g_get_real_name (void);
const gchar* g_get_user_cache_dir (void);
const gchar* g_get_user_data_dir (void);
const gchar* g_get_user_config_dir (void);
enum GUserDirectory;
const gchar* g_get_user_special_dir (GUserDirectory directory);
const gchar* const * g_get_system_data_dirs (void);
const gchar* const * g_get_system_config_dirs (void);
void g_reload_user_special_dirs_cache (void);

const gchar* g_get_host_name (void);
const gchar* g_get_home_dir (void);
const gchar* g_get_tmp_dir (void);
gchar* g_get_current_dir (void);
const gchar* g_basename (const gchar *file_name);
#define g_dirname
gboolean g_path_is_absolute (const gchar *file_name);
const gchar* g_path_skip_root (const gchar *file_name);
gchar* g_path_get_basename (const gchar *file_name);
gchar* g_path_get_dirname (const gchar *file_name);
gchar * g_build_filename (const gchar *first_element,
...);
gchar * g_build_filenamev (gchar **args);
gchar * g_build_path (const gchar *separator,
const gchar *first_element,
...);
gchar * g_build_pathv (const gchar *separator,
gchar **args);
char * g_format_size_for_display (goffset size);

gchar* g_find_program_in_path (const gchar *program);

gint g_bit_nth_lsf (gulong mask,
gint nth_bit);
gint g_bit_nth_msf (gulong mask,
gint nth_bit);
guint g_bit_storage (gulong number);

guint g_spaced_primes_closest (guint num);

void g_atexit (GVoidFunc func);

guint g_parse_debug_string (const gchar *string,
const GDebugKey *keys,
guint nkeys);
GDebugKey;

void (*GVoidFunc) (void);
void (*GFreeFunc) (gpointer data);

void g_qsort_with_data (gconstpointer pbase,
gint total_elems,
gsize size,
GCompareDataFunc compare_func,
gpointer user_data);

void g_nullify_pointer (gpointer *nullify_location);

說明

這些是可移植的實用函式。

細節

g_get_application_name ()

const gchar*        g_get_application_name              (void);

取得應用程式人們可讀取的名稱,這名稱是由g_set_application_name()設定,如果可以的話這個名稱應該是區域性的,且用來顯示給使用者的,與g_get_prgname()相比,這個函式取得非區域性的名稱,假如g_set_application_name() 沒有被呼叫,傳回g_get_prgname() 的結果(如果g_set_prgname()也沒有被呼叫那就會是NULL)。

傳回:

人們可讀取的應用程式名稱,可能傳回NULL

2.2版以後使用


g_set_application_name ()

void                g_set_application_name              (const gchar *application_name);

設定應用程式名稱為人們可讀取的,如果可能的話這個名稱應該是區域性的,並且用來顯示給使用者看,與g_set_prgname()相比,這是用來設定非區域性的名稱,g_set_prgname() 會自動由 gtk_init()呼叫,但是 g_set_application_name() 不會。

注意因為執行緒安全的考量,這個函式只能被呼叫一次。

應用程式名稱用於像是錯誤訊息的內容,或是在工作列顯示應用程式的名稱。

應用程式:

應用程式的區域性名稱

2.2以後


g_get_prgname ()

gchar*              g_get_prgname                       (void);

取得程式的名稱,與 g_get_application_name()相比這程式不應該是區域性的。(假如你使用GDK或GTK+ 程式名稱是由gdk_init()設定,這個函式是由gtk_init()呼叫,程式名稱藉由argv[0]的最後一個部份來發現)

傳回:

程式的名稱,傳回的字串屬於GLib而且不能修改或釋放。

g_set_prgname ()

void                g_set_prgname                       (const gchar *prgname);

設定程式名稱,與 g_set_application_name()這名稱不應是區域性的,注意基於執行緒安全性考量這函式只能被呼叫一次。

prgname :

程式的名稱。

g_getenv ()

const gchar*        g_getenv                            (const gchar *variable);

傳回環境變數的值,名稱跟值是用GLib檔案名稱編碼,在UNIX上,這意味著實際的字元可能或不可能是某些一致的字元集和編碼,在Windows上,是UTF-8編碼,在Windows上,如果環境變數的值包含參考其他的環境變數,他們就會展開。

變數::

環境變數的取得是以GLib檔案名稱編碼。

傳回:

環境變數的值,或是假如環境變數沒有找到就傳回NULL,傳回的字串會被接下來的g_getenv()g_setenv()g_unsetenv() 呼叫所覆蓋。

g_setenv ()

gboolean            g_setenv                            (const gchar *variable,
const gchar *value,
gboolean overwrite);

設定一個環境變數,變數的名稱跟值是以GLib檔案名稱來編碼,在UNIX上,這意味著它們是任意的序列字元,在Windows上,應該是以UTF-8編碼。

注意在某些系統上,當變數被覆寫,前一個變數跟它的值所使用的記憶體不會被回收。

變數:

環境變數的設定,必須不包含'='。

值:

設定變數的值。

複寫:

假如變數已存在是否改變變數。

傳回:

假如環境變數沒有被設定傳回FALSE

2.4版以後才有


g_unsetenv ()

void                g_unsetenv                          (const gchar *variable);

移除環境變數。

注意在某些系統上,當變數被覆寫時,前一個變數跟值所使用的記憶體不能被回收,此外,這個函式不保證在執行緒安全模式下操作。

變數:

環境變數的移除不能魽有'='。

2.4版以後使用。


g_listenv ()

gchar**             g_listenv                           (void);

取得所有環境變數的名稱

傳回:

必須是 g_strfreev()釋放的一個以NULL-結尾的字串列表,要移植到Windows的程式通常使用這個函式跟g_getenv() 而不是直接使用C函式庫的environ陣列,在Windows上,在wnviron陣列中的字串是以系統代碼夜來編碼,而在最典型的使用案例中對於使用GLib程式的環境變數你會想要使用這個函式跟g_getenv() 提供的UTF-8編碼。

2.8以後使用


g_get_user_name ()

const gchar*        g_get_user_name                     (void);

取得目前使用者的名稱,傳回字串的編碼是系統定義的,在UNIX上,可能是首選的檔案名稱編碼,或是其他的,這甚至在一致的機器上也不能保證,在Windows上,它總是使用UTF-8。

傳回:

目前的使用者名稱。

g_get_real_name ()

const gchar*        g_get_real_name                     (void);

取得使用者的真實名稱,這個名稱通常來自passwd檔的使用者紀錄,傳回字串的編碼是系統定義的,(然而在Windows上一定是使用UTF-8),假如真實的使用者名稱沒有定義,會傳回"Unknown"字串。

傳回:

使用者的真實名稱。

g_get_user_cache_dir ()

const gchar*        g_get_user_cache_dir                (void);

傳回儲存特定使用者非必要的暫存資料所在的基本目錄。

在UNIX平台上,使用 XDG基本目錄規範 來定義。

傳回:

GLib所擁有的字串不能被修改或釋放。

2.6以後使用


g_get_user_data_dir ()

const gchar*        g_get_user_data_dir                 (void);

傳回像是特定使用者所自訂的圖示等的應用程式資料所在的基本目錄。

在UNIX平台上使用 XDG Base Directory Specification規範定義。

傳回:

GLib的字串不可修改或釋放。

2.6版後使用


g_get_user_config_dir ()

const gchar*        g_get_user_config_dir               (void);

傳回儲存使用者特定的應用程式的組態資訊像是使用者的偏好設定之類的基本目錄。

在UNIX平台上使用 XDG 基本目錄規範 來定義。 

傳回:

GLib的字串不可修改或釋放。

Since 2.6


enum GUserDirectory

typedef enum {
G_USER_DIRECTORY_DESKTOP,
G_USER_DIRECTORY_DOCUMENTS,
G_USER_DIRECTORY_DOWNLOAD,
G_USER_DIRECTORY_MUSIC,
G_USER_DIRECTORY_PICTURES,
G_USER_DIRECTORY_PUBLIC_SHARE,
G_USER_DIRECTORY_TEMPLATES,
G_USER_DIRECTORY_VIDEOS,

G_USER_N_DIRECTORIES
} GUserDirectory;

These are logical ids for special directories which are defined depending on the platform used. You should use g_get_user_special_dir() to retrieve the full path associated to the logical id.

The GUserDirectory enumeration can be extended at later date. Not every platform has a directory for every logical id in this enumeration.

G_USER_DIRECTORY_DESKTOP

the user's Desktop directory

G_USER_DIRECTORY_DOCUMENTS

the user's Documents directory

G_USER_DIRECTORY_DOWNLOAD

the user's Downloads directory

G_USER_DIRECTORY_MUSIC

the user's Music directory

G_USER_DIRECTORY_PICTURES

the user's Pictures directory

G_USER_DIRECTORY_PUBLIC_SHARE

the user's shared directory

G_USER_DIRECTORY_TEMPLATES

the user's Templates directory

G_USER_DIRECTORY_VIDEOS

the user's Movies directory

G_USER_N_DIRECTORIES

the number of enum values

Since 2.14


g_get_user_special_dir ()

const gchar*        g_get_user_special_dir              (GUserDirectory directory);

Returns the full path of a special directory using its logical id.

On Unix this is done using the XDG special user directories. For compatibility with existing practise, G_USER_DIRECTORY_DESKTOP falls back to $HOME/Desktop when XDG special user directories have not been set up.

Depending on the platform, the user might be able to change the path of the special directory without requiring the session to restart; GLib will not reflect any change once the special directories are loaded.

directory :

the logical id of special directory

Returns :

the path to the specified special directory, or NULL if the logical id was not found. The returned string is owned by GLib and should not be modified or freed.

Since 2.14


g_get_system_data_dirs ()

const gchar* const * g_get_system_data_dirs             (void);

Returns an ordered list of base directories in which to access system-wide application data.

On UNIX platforms this is determined using the mechanisms described in the XDG Base Directory Specification

On Windows the first elements in the list are the Application Data and Documents folders for All Users. (These can be determined only on Windows 2000 or later and are not present in the list on other Windows versions.) See documentation for CSIDL_COMMON_APPDATA and CSIDL_COMMON_DOCUMENTS.

Then follows the "share" subfolder in the installation folder for the package containing the DLL that calls this function, if it can be determined.

Finally the list contains the "share" subfolder in the installation folder for GLib, and in the installation folder for the package the application's .exe file belongs to.

The installation folders above are determined by looking up the folder where the module (DLL or EXE) in question is located. If the folder's name is "bin", its parent is used, otherwise the folder itself.

Note that on Windows the returned list can vary depending on where this function is called.

Returns :

a NULL-terminated array of strings owned by GLib that must not be modified or freed.

Since 2.6


g_get_system_config_dirs ()

const gchar* const * g_get_system_config_dirs           (void);

Returns an ordered list of base directories in which to access system-wide configuration information.

On UNIX platforms this is determined using the mechanisms described in the XDG Base Directory Specification

Returns :

a NULL-terminated array of strings owned by GLib that must not be modified or freed.

Since 2.6


g_reload_user_special_dirs_cache ()

void                g_reload_user_special_dirs_cache    (void);

Resets the cache used for g_get_user_special_dir(), so that the latest on-disk version is used. Call this only if you just changed the data on disk yourself.

Due to threadsafety issues this may cause leaking of strings that were previously returned from g_get_user_special_dir() that can't be freed. We ensure to only leak the data for the directories that actually changed value though.

Since 2.22


g_get_host_name ()

const gchar*        g_get_host_name                     (void);

Return a name for the machine.

The returned name is not necessarily a fully-qualified domain name, or even present in DNS or some other name service at all. It need not even be unique on your local network or site, but usually it is. Callers should not rely on the return value having any specific properties like uniqueness for security purposes. Even if the name of the machine is changed while an application is running, the return value from this function does not change. The returned string is owned by GLib and should not be modified or freed. If no name can be determined, a default fixed string "localhost" is returned.

Returns :

the host name of the machine.

Since 2.8


g_get_home_dir ()

const gchar*        g_get_home_dir                      (void);

取得定義在password資料庫中的使用者根目錄。

注意對照於傳統的UNIX工具,這個函式較喜歡passwd紀錄的HOME環境變數

這樣決定的一個理由就是再很多情況下應用程式需要特殊處理來處理HOME在下面的情況:

Not owned by the user
Not writeable
Not even readable

由於應用程式一般不能寫入來處理這些情況,所以不要用 g_get_home_dir()來關注HOME是較好的,而且可以傳回真正的使用者根目錄,假如應用程式要專注HOME,他們可以這樣寫:

1
2
3
const char *homedir = g_getenv ("HOME");
if (!homedir)
homedir = g_get_home_dir ();

Returns :

使用者的根目錄

g_get_tmp_dir ()

const gchar*        g_get_tmp_dir                       (void);

Gets the directory to use for temporary files. This is found from inspecting the environment variables TMPDIR, TMP, and TEMP in that order. If none of those are defined "/tmp" is returned on UNIX and "C:\" on Windows. The encoding of the returned string is system-defined. On Windows, it is always UTF-8. The return value is never NULL.

Returns :

the directory to use for temporary files.

g_get_current_dir ()

gchar*              g_get_current_dir                   (void);

Gets the current directory. The returned string should be freed when no longer needed. The encoding of the returned string is system defined. On Windows, it is always UTF-8.

Returns :

the current directory.

g_basename ()

const gchar*        g_basename                          (const gchar *file_name);

Warning

g_basename has been deprecated since version 2.2 and should not be used in newly-written code. Use g_path_get_basename() instead, but notice that g_path_get_basename() allocates new memory for the returned string, unlike this function which returns a pointer into the argument.

Gets the name of the file without any leading directory components. It returns a pointer into the given file name string.

file_name :

the name of the file.

Returns :

the name of the file without any leading directory components.

g_dirname

#define             g_dirname

Warning

g_dirname is deprecated and should not be used in newly-written code.

This function is deprecated and will be removed in the next major release of GLib. Use g_path_get_dirname() instead.

Gets the directory components of a file name. If the file name has no directory components "." is returned. The returned string should be freed when no longer needed.

Returns :

the directory components of the file.

g_path_is_absolute ()

gboolean            g_path_is_absolute                  (const gchar *file_name);

Returns TRUE if the given file_name is an absolute file name, i.e. it contains a full path from the root directory such as "/usr/local" on UNIX or "C:\windows" on Windows systems.

file_name :

a file name.

Returns :

TRUE if file_name is an absolute path.

g_path_skip_root ()

const gchar*        g_path_skip_root                    (const gchar *file_name);

Returns a pointer into file_name after the root component, i.e. after the "/" in UNIX or "C:\" under Windows. If file_name is not an absolute path it returns NULL.

file_name :

a file name.

傳回:

a pointer into file_name after the root component.

g_path_get_basename ()

gchar*              g_path_get_basename                 (const gchar *file_name);

Gets the last component of the filename. If file_name ends with a directory separator it gets the component before the last slash. If file_name consists only of directory separators (and on Windows, possibly a drive letter), a single separator is returned. If file_name is empty, it gets ".".

file_name :

檔案的名稱。

Returns :

a newly allocated string containing the last component of the filename.

g_path_get_dirname ()

gchar*              g_path_get_dirname                  (const gchar *file_name);

取得檔案名稱的目錄部份,假如檔案名稱沒有目錄的部份會傳回 ".",這個傳回的字串不再使用時會釋放出來。

file_name :

檔案的名稱。

傳回::

檔案的目錄部份。

g_build_filename ()

gchar *             g_build_filename                    (const gchar *first_element,
...);

從一系列正確使用分隔符號的檔名元素來建構一個檔案名稱。

在Unix上,這個函式跟g_build_path (G_DIR_SEPARATOR_S, first_element, ....)作用一樣。

在Windows上,它會考慮到要用反斜線 (\ 或是斜線 (/) 來作為檔名的分隔符號,但是在Unix則是一致,當檔案的路徑名稱分隔符號需要插入時,先前出現在參數最後一個分隔符 (由左到右這樣讀)會使用。

不要嘗試強迫結果的檔名會是絕對路徑,假如第一個元素事相對路徑,結果也會是有相對路徑。

first_element :

the first element in the path

... :

remaining elements in path, terminated by NULL

Returns :

a newly-allocated string that must be freed with g_free().

g_build_filenamev ()

gchar *             g_build_filenamev                   (gchar **args);

Behaves exactly like g_build_filename(), but takes the path elements as a string array, instead of varargs. This function is mainly meant for language bindings.

args :

NULL-terminated array of strings containing the path elements.

Returns :

a newly-allocated string that must be freed with g_free().

Since 2.8


g_build_path ()

gchar *             g_build_path                        (const gchar *separator,
const gchar *first_element,
...);

Creates a path from a series of elements using separator as the separator between elements. At the boundary between two elements, any trailing occurrences of separator in the first element, or leading occurrences of separator in the second element are removed and exactly one copy of the separator is inserted.

Empty elements are ignored.

The number of leading copies of the separator on the result is the same as the number of leading copies of the separator on the first non-empty element.

The number of trailing copies of the separator on the result is the same as the number of trailing copies of the separator on the last non-empty element. (Determination of the number of trailing copies is done without stripping leading copies, so if the separator is ABA, ABABA has 1 trailing copy.)

However, if there is only a single non-empty element, and there are no characters in that element not part of the leading or trailing separators, then the result is exactly the original value of that element.

Other than for determination of the number of leading and trailing copies of the separator, elements consisting only of copies of the separator are ignored.

separator :

a string used to separator the elements of the path.

first_element :

the first element in the path

... :

remaining elements in path, terminated by NULL

Returns :

a newly-allocated string that must be freed with g_free().

g_build_pathv ()

gchar *             g_build_pathv                       (const gchar *separator,
gchar **args);

Behaves exactly like g_build_path(), but takes the path elements as a string array, instead of varargs. This function is mainly meant for language bindings.

separator :

a string used to separator the elements of the path.

args :

NULL-terminated array of strings containing the path elements.

Returns :

a newly-allocated string that must be freed with g_free().

Since 2.8


g_format_size_for_display ()

char *              g_format_size_for_display           (goffset size);

Formats a size (for example the size of a file) into a human readable string. Sizes are rounded to the nearest size prefix (KB, MB, GB) and are displayed rounded to the nearest tenth. E.g. the file size 3292528 bytes will be converted into the string "3.1 MB".

The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).

This string should be freed with g_free() when not needed any longer.

size :

a size in bytes.

Returns :

a newly-allocated formatted string containing a human readable file size.

Since 2.16


g_find_program_in_path ()

gchar*              g_find_program_in_path              (const gchar *program);

Locates the first executable named program in the user's path, in the same way that execvp() would locate it. Returns an allocated string with the absolute path name, or NULL if the program is not found in the path. If program is already an absolute path, returns a copy of program if program exists and is executable, and NULL otherwise. On Windows, if program does not have a file type suffix, tries with the suffixes .exe, .cmd, .bat and .com, and the suffixes in the PATHEXT environment variable.

On Windows, it looks for the file in the same way as CreateProcess() would. This means first in the directory where the executing program was loaded from, then in the current directory, then in the Windows 32-bit system directory, then in the Windows directory, and finally in the directories in the PATH environment variable. If the program is found, the return value contains the full name including the type suffix.

program :

a program name in the GLib file name encoding

Returns :

absolute path, or NULL

g_bit_nth_lsf ()

gint                g_bit_nth_lsf                       (gulong mask,
gint nth_bit);

Find the position of the first bit set in mask, searching from (but not including) nth_bit upwards. Bits are numbered from 0 (least significant) to sizeof(gulong) * 8 - 1 (31 or 63, usually). To start searching from the 0th bit, set nth_bit to -1.

mask :

a gulong containing flags.

nth_bit :

the index of the bit to start the search from.

Returns :

the index of the first bit set which is higher than nth_bit.

g_bit_nth_msf ()

gint                g_bit_nth_msf                       (gulong mask,
gint nth_bit);

Find the position of the first bit set in mask, searching from (but not including) nth_bit downwards. Bits are numbered from 0 (least significant) to sizeof(gulong) * 8 - 1 (31 or 63, usually). To start searching from the last bit, set nth_bit to -1 or GLIB_SIZEOF_LONG * 8.

mask :

a gulong containing flags.

nth_bit :

the index of the bit to start the search from.

Returns :

the index of the first bit set which is lower than nth_bit.

g_bit_storage ()

guint               g_bit_storage                       (gulong number);

Gets the number of bits used to hold number, e.g. if number is 4, 3 bits are needed.

number :

a guint.

Returns :

the number of bits used to hold number.

g_spaced_primes_closest ()

guint               g_spaced_primes_closest             (guint num);

Gets the smallest prime number from a built-in array of primes which is larger than num. This is used within GLib to calculate the optimum size of a GHashTable.

The built-in array of primes ranges from 11 to 13845163 such that each prime is approximately 1.5-2 times the previous prime.

num :

a guint.

Returns :

the smallest prime number from a built-in array of primes which is larger than num.

g_atexit ()

void                g_atexit                            (GVoidFunc func);

Specifies a function to be called at normal program termination.

Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor macro that maps to a call to the atexit() function in the C library. This means that in case the code that calls g_atexit(), i.e. atexit(), is in a DLL, the function will be called when the DLL is detached from the program. This typically makes more sense than that the function is called when the GLib DLL is detached, which happened earlier when g_atexit() was a function in the GLib DLL.

The behaviour of atexit() in the context of dynamically loaded modules is not formally specified and varies wildly.

On POSIX systems, calling g_atexit() (or atexit()) in a dynamically loaded module which is unloaded before the program terminates might well cause a crash at program exit.

Some POSIX systems implement atexit() like Windows, and have each dynamically loaded module maintain an own atexit chain that is called when the module is unloaded.

On other POSIX systems, before a dynamically loaded module is unloaded, the registered atexit functions (if any) residing in that module are called, regardless where the code that registered them resided. This is presumably the most robust approach.

As can be seen from the above, for portability it's best to avoid calling g_atexit() (or atexit()) except in the main executable of a program.

func :

the function to call on normal program termination.

g_parse_debug_string ()

guint               g_parse_debug_string                (const gchar *string,
const GDebugKey *keys,
guint nkeys);

Parses a string containing debugging options into a guint containing bit flags. This is used within GDK and GTK+ to parse the debug options passed on the command line or through environment variables.

If string is equal to "all", all flags are set. If string is equal to "help", all the available keys in keys are printed out to standard error.

string :

a list of debug options separated by colons, spaces, or commas, or NULL.

keys :

pointer to an array of GDebugKey which associate strings with bit flags.

nkeys :

the number of GDebugKeys in the array.

Returns :

the combined set of bit flags.

GDebugKey

typedef struct {
const gchar *key;
guint value;
} GDebugKey;

Associates a string with a bit flag. Used in g_parse_debug_string().

const gchar *key;

the string

guint value;

the flag

GVoidFunc ()

void                (*GVoidFunc)                        (void);

Declares a type of function which takes no arguments and has no return value. It is used to specify the type function passed to g_atexit().


GFreeFunc ()

void                (*GFreeFunc)                        (gpointer data);

Declares a type of function which takes an arbitrary data pointer argument and has no return value. It is not currently used in GLib or GTK+.

data :

a data pointer.

g_qsort_with_data ()

void                g_qsort_with_data                   (gconstpointer pbase,
gint total_elems,
gsize size,
GCompareDataFunc compare_func,
gpointer user_data);

This is just like the standard C qsort() function, but the comparison routine accepts a user data argument.

pbase :

start of array to sort

total_elems :

elements in the array

size :

size of each element

compare_func :

function to compare elements

user_data :

data to pass to compare_func

g_nullify_pointer ()

void                g_nullify_pointer                   (gpointer *nullify_location);

Set the pointer at the specified location to NULL.

nullify_location :

the memory address of the pointer.

File Utilities

File Utilities

File Utilities — 各種檔案相關的函式


總覽

#include <glib.h>
#include <glib/gstdio.h>

enum GFileError;
#define G_FILE_ERROR
enum GFileTest;
GFileError g_file_error_from_errno (gint err_no);
gboolean g_file_get_contents (const gchar *filename,
gchar **contents,
gsize *length,
GError **error);
gboolean g_file_set_contents (const gchar *filename,
const gchar *contents,
gssize length,
GError **error);
gboolean g_file_test (const gchar *filename,
GFileTest test);
gint g_mkstemp (gchar *tmpl);
gint g_mkstemp_full (gchar *tmpl,
int flags,
int mode);
gint g_file_open_tmp (const gchar *tmpl,
gchar **name_used,
GError **error);
gchar * g_file_read_link (const gchar *filename,
GError **error);
int g_mkdir_with_parents (const gchar *pathname,
int mode);

GDir;
GDir * g_dir_open (const gchar *path,
guint flags,
GError **error);
const gchar * g_dir_read_name (GDir *dir);
void g_dir_rewind (GDir *dir);
void g_dir_close (GDir *dir);

GMappedFile;
GMappedFile * g_mapped_file_new (const gchar *filename,
gboolean writable,
GError **error);
GMappedFile * g_mapped_file_ref (GMappedFile *file);
void g_mapped_file_unref (GMappedFile *file);
void g_mapped_file_free (GMappedFile *file);
gsize g_mapped_file_get_length (GMappedFile *file);
gchar * g_mapped_file_get_contents (GMappedFile *file);

int g_open (const gchar *filename,
int flags,
int mode);
int g_rename (const gchar *oldfilename,
const gchar *newfilename);
int g_mkdir (const gchar *filename,
int mode);
int g_stat (const gchar *filename,
struct _g_stat_struct *buf);
int g_lstat (const gchar *filename,
struct _g_stat_struct *buf);
int g_unlink (const gchar *filename);
int g_remove (const gchar *filename);
int g_rmdir (const gchar *filename);
FILE * g_fopen (const gchar *filename,
const gchar *mode);
FILE * g_freopen (const gchar *filename,
const gchar *mode,
FILE *stream);
int g_chmod (const gchar *filename,
int mode);
int g_access (const gchar *filename,
int mode);
int g_creat (const gchar *filename,
int mode);
int g_chdir (const gchar *path);
int g_utime (const gchar *filename,
struct utimbuf *utb);

Description

There is a group of functions which wrap the common POSIX functions dealing with filenames (g_open(), g_rename(), g_mkdir(), g_stat(), g_unlink(), g_remove(), g_fopen(), g_freopen()). The point of these wrappers is to make it possible to handle file names with any Unicode characters in them on Windows without having to use ifdefs and the wide character API in the application code.

The pathname argument should be in the GLib file name encoding. On POSIX this is the actual on-disk encoding which might correspond to the locale settings of the process (or the G_FILENAME_ENCODING environment variable), or not.

On Windows the GLib file name encoding is UTF-8. Note that the Microsoft C library does not use UTF-8, but has separate APIs for current system code page and wide characters (UTF-16). The GLib wrappers call the wide character API if present (on modern Windows systems), otherwise convert to/from the system code page.

Another group of functions allows to open and read directories in the GLib file name encoding. These are g_dir_open(), g_dir_read_name(), g_dir_rewind(), g_dir_close().

Details

enum GFileError

typedef enum
{
G_FILE_ERROR_EXIST,
G_FILE_ERROR_ISDIR,
G_FILE_ERROR_ACCES,
G_FILE_ERROR_NAMETOOLONG,
G_FILE_ERROR_NOENT,
G_FILE_ERROR_NOTDIR,
G_FILE_ERROR_NXIO,
G_FILE_ERROR_NODEV,
G_FILE_ERROR_ROFS,
G_FILE_ERROR_TXTBSY,
G_FILE_ERROR_FAULT,
G_FILE_ERROR_LOOP,
G_FILE_ERROR_NOSPC,
G_FILE_ERROR_NOMEM,
G_FILE_ERROR_MFILE,
G_FILE_ERROR_NFILE,
G_FILE_ERROR_BADF,
G_FILE_ERROR_INVAL,
G_FILE_ERROR_PIPE,
G_FILE_ERROR_AGAIN,
G_FILE_ERROR_INTR,
G_FILE_ERROR_IO,
G_FILE_ERROR_PERM,
G_FILE_ERROR_NOSYS,
G_FILE_ERROR_FAILED
} GFileError;

Values corresponding to errno codes returned from file operations on UNIX. Unlike errno codes, GFileError values are available on all systems, even Windows. The exact meaning of each code depends on what sort of file operation you were performing; the UNIX documentation gives more details. The following error code descriptions come from the GNU C Library manual, and are under the copyright of that manual.

It's not very portable to make detailed assumptions about exactly which errors will be returned from a given operation. Some errors don't occur on some systems, etc., sometimes there are subtle differences in when a system will report a given error, etc.

G_FILE_ERROR_EXIST

Operation not permitted; only the owner of the file (or other resource) or processes with special privileges can perform the operation.

G_FILE_ERROR_ISDIR

File is a directory; you cannot open a directory for writing, or create or remove hard links to it.

G_FILE_ERROR_ACCES

Permission denied; the file permissions do not allow the attempted operation.

G_FILE_ERROR_NAMETOOLONG

Filename too long.

G_FILE_ERROR_NOENT

No such file or directory. This is a "file doesn't exist" error for ordinary files that are referenced in contexts where they are expected to already exist.

G_FILE_ERROR_NOTDIR

A file that isn't a directory was specified when a directory is required.

G_FILE_ERROR_NXIO

No such device or address. The system tried to use the device represented by a file you specified, and it couldn't find the device. This can mean that the device file was installed incorrectly, or that the physical device is missing or not correctly attached to the computer.

G_FILE_ERROR_NODEV

This file is of a type that doesn't support mapping.

G_FILE_ERROR_ROFS

The directory containing the new link can't be modified because it's on a read-only file system.

G_FILE_ERROR_TXTBSY

Text file busy.

G_FILE_ERROR_FAULT

You passed in a pointer to bad memory. (GLib won't reliably return this, don't pass in pointers to bad memory.)

G_FILE_ERROR_LOOP

Too many levels of symbolic links were encountered in looking up a file name. This often indicates a cycle of symbolic links.

G_FILE_ERROR_NOSPC

No space left on device; write operation on a file failed because the disk is full.

G_FILE_ERROR_NOMEM

No memory available. The system cannot allocate more virtual memory because its capacity is full.

G_FILE_ERROR_MFILE

The current process has too many files open and can't open any more. Duplicate descriptors do count toward this limit.

G_FILE_ERROR_NFILE

There are too many distinct file openings in the entire system.

G_FILE_ERROR_BADF

Bad file descriptor; for example, I/O on a descriptor that has been closed or reading from a descriptor open only for writing (or vice versa).

G_FILE_ERROR_INVAL

Invalid argument. This is used to indicate various kinds of problems with passing the wrong argument to a library function.

G_FILE_ERROR_PIPE

Broken pipe; there is no process reading from the other end of a pipe. Every library function that returns this error code also generates a `SIGPIPE' signal; this signal terminates the program if not handled or blocked. Thus, your program will never actually see this code unless it has handled or blocked `SIGPIPE'.

G_FILE_ERROR_AGAIN

Resource temporarily unavailable; the call might work if you try again later.

G_FILE_ERROR_INTR

Interrupted function call; an asynchronous signal occurred and prevented completion of the call. When this happens, you should try the call again.

G_FILE_ERROR_IO

Input/output error; usually used for physical read or write errors. i.e. the disk or other physical device hardware is returning errors.

G_FILE_ERROR_PERM

Operation not permitted; only the owner of the file (or other resource) or processes with special privileges can perform the operation.

G_FILE_ERROR_NOSYS

Function not implemented; this indicates that the system is missing some functionality.

G_FILE_ERROR_FAILED

Does not correspond to a UNIX error code; this is the standard "failed for unspecified reason" error code present in all GError error code enumerations. Returned if no specific code applies.

G_FILE_ERROR

#define G_FILE_ERROR g_file_error_quark ()

Error domain for file operations. Errors in this domain will be from the GFileError enumeration. See GError for information on error domains.


enum GFileTest

typedef enum
{
G_FILE_TEST_IS_REGULAR = 1 << 0,
G_FILE_TEST_IS_SYMLINK = 1 << 1,
G_FILE_TEST_IS_DIR = 1 << 2,
G_FILE_TEST_IS_EXECUTABLE = 1 << 3,
G_FILE_TEST_EXISTS = 1 << 4
} GFileTest;

在檔案上使用g_file_test()來執行測試。

G_FILE_TEST_IS_REGULAR

假如檔案是一般檔案(不是目錄)則為TRUE ,注意假如這個測試檔案是一個連到一般檔案的符號連結時也會傳回TRUE

G_FILE_TEST_IS_SYMLINK

檔案是符號連結檔則為TRUE

G_FILE_TEST_IS_DIR

檔案是目錄則為TRUE

G_FILE_TEST_IS_EXECUTABLE

假如檔案是可執行檔則為TRUE

G_FILE_TEST_EXISTS

檔案是否存在,假如檔案存在傳回TRUE,它可以是或不可以是一般檔案。

g_file_error_from_errno ()

GFileError          g_file_error_from_errno             (gint err_no);

Gets a GFileError constant based on the passed-in errno. For example, if you pass in EEXIST this function returns G_FILE_ERROR_EXIST. Unlike errno values, you can portably assume that all GFileError values will exist.

Normally a GFileError value goes into a GError returned from a function that manipulates files. So you would use g_file_error_from_errno() when constructing a GError.

err_no :

an "errno" value

Returns :

GFileError corresponding to the given errno

g_file_get_contents ()

gboolean            g_file_get_contents                 (const gchar *filename,
gchar **contents,
gsize *length,
GError **error);

Reads an entire file into allocated memory, with good error checking.

If the call was successful, it returns TRUE and sets contents to the file contents and length to the length of the file contents in bytes. The string stored in contents will be nul-terminated, so for text files you can pass NULL for the length argument. If the call was not successful, it returns FALSE and sets error. The error domain is G_FILE_ERROR. Possible error codes are those in the GFileError enumeration. In the error case, contents is set to NULL and length is set to zero.

filename :

name of a file to read contents from, in the GLib file name encoding

contents :

location to store an allocated string, use g_free() to free the returned string

length :

location to store length in bytes of the contents, or NULL

error :

return location for a GError, or NULL

Returns :

TRUE on success, FALSE if an error occurred

g_file_set_contents ()

gboolean            g_file_set_contents                 (const gchar *filename,
const gchar *contents,
gssize length,
GError **error);

Writes all of contents to a file named filename, with good error checking. If a file called filename already exists it will be overwritten.

This write is atomic in the sense that it is first written to a temporary file which is then renamed to the final name. Notes:

  • On Unix, if filename already exists hard links to filename will break. Also since the file is recreated, existing permissions, access control lists, metadata etc. may be lost. If filename is a symbolic link, the link itself will be replaced, not the linked file.
  • On Windows renaming a file will not remove an existing file with the new name, so on Windows there is a race condition between the existing file being removed and the temporary file being renamed.
  • On Windows there is no way to remove a file that is open to some process, or mapped into memory. Thus, this function will fail if filename already exists and is open.

 

If the call was sucessful, it returns TRUE. If the call was not successful, it returns FALSE and sets error. The error domain is G_FILE_ERROR. Possible error codes are those in the GFileError enumeration.

filename :

name of a file to write contents to, in the GLib file name encoding

contents :

string to write to the file

length :

length of contents, or -1 if contents is a nul-terminated string

error :

return location for a GError, or NULL

Returns :

TRUE on success, FALSE if an error occurred

Since 2.8


g_file_test ()

gboolean            g_file_test                         (const gchar *filename,
GFileTest test);

假如在位元欄位test 中的任何測試是TRUE就傳回TRUE,例如:假如檔案存在,(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR) 會傳回 TRUE;由於存在測試是TRUE所以檢查是否是目錄就沒那要緊,隨著當前可用的測試集,一次通過一個以上的測試毫無意義。

除了G_FILE_TEST_IS_SYMLINK所有測試遵循符號連結,如此對於G_FILE_TEST_IS_SYMLINKG_FILE_TEST_IS_REGULAR.來說一個符號連結到一個普通檔案 g_file_test() 會傳回TRUE

注意,對於一個懸掛的符號連結g_file_test() 使用G_FILE_TEST_IS_SYMLINK會傳回TRUE ,而使用其他的旗標會傳回FALSE

你不應該使用g_file_test()來測試它是否可以安全地進行操作,因為在你真正執行操作前總是有狀況改變的可能性發生,例如,你可能會認為你可以使用G_FILE_TEST_IS_SYMLINK 知道它是否可以安全的寫入檔案,而不會被欺騙寫到不同的位置,但是這根本不好用

/* DON'T DO THIS */
if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK))
{
fd = g_open (filename, O_WRONLY);
/* write to fd */
}

 

另一件要注意的事是G_FILE_TEST_EXISTSG_FILE_TEST_IS_EXECUTABLE是使用access()系統呼叫來執行的,這通常沒什麼關係,但是假如你的程式是setuid(設定使用者ID)或是setgid(設定群組ID)的程式意味著這些測試會給你真實的使用者ID跟群組ID的答案,而不是有效的使用者ID跟群組ID。

在Windows沒有符號連結,所以測試G_FILE_TEST_IS_SYMLINK會傳回FALSE,測試G_FILE_TEST_IS_EXECUTABLE只會檢查檔案存在以及它的檔名是否可執行,檢查眾所周知的副檔名以及列在PATHEXT環境變數中所列的檔名。

filename :

測試在GLib檔名編碼中的檔名

test :

GFileTest 位元欄位的旗標

傳回 :

測試是否為TRUE

g_mkstemp ()

gint                g_mkstemp                           (gchar *tmpl);

Opens a temporary file. See the mkstemp() documentation on most UNIX-like systems.

The parameter is a string that should follow the rules for mkstemp() templates, i.e. contain the string "XXXXXX". g_mkstemp() is slightly more flexible than mkstemp() in that the sequence does not have to occur at the very end of the template. The X string will be modified to form the name of a file that didn't exist. The string should be in the GLib file name encoding. Most importantly, on Windows it should be in UTF-8.

tmpl :

template filename

Returns :

A file handle (as from open()) to the file opened for reading and writing. The file is opened in binary mode on platforms where there is a difference. The file handle should be closed with close(). In case of errors, -1 is returned.

g_mkstemp_full ()

gint                g_mkstemp_full                      (gchar *tmpl,
int flags,
int mode);

Opens a temporary file. See the mkstemp() documentation on most UNIX-like systems.

The parameter is a string that should follow the rules for mkstemp() templates, i.e. contain the string "XXXXXX". g_mkstemp_full() is slightly more flexible than mkstemp() in that the sequence does not have to occur at the very end of the template and you can pass a mode and additional flags. The X string will be modified to form the name of a file that didn't exist. The string should be in the GLib file name encoding. Most importantly, on Windows it should be in UTF-8.

tmpl :

template filename

flags :

flags to pass to an open() call in addition to O_EXCL and O_CREAT, which are passed automatically

mode :

permissios to create the temporary file with

Returns :

A file handle (as from open()) to the file opened for reading and writing. The file handle should be closed with close(). In case of errors, -1 is returned.

Since 2.22


g_file_open_tmp ()

gint                g_file_open_tmp                     (const gchar *tmpl,
gchar **name_used,
GError **error);

Opens a file for writing in the preferred directory for temporary files (as returned by g_get_tmp_dir()).

tmpl should be a string in the GLib file name encoding containing a sequence of six 'X' characters, as the parameter to g_mkstemp(). However, unlike these functions, the template should only be a basename, no directory components are allowed. If template is NULL, a default template is used.

Note that in contrast to g_mkstemp() (and mkstemp()) tmpl is not modified, and might thus be a read-only literal string.

The actual name used is returned in name_used if non-NULL. This string should be freed with g_free() when not needed any longer. The returned name is in the GLib file name encoding.

tmpl :

Template for file name, as in g_mkstemp(), basename only, or NULL, to a default template

name_used :

location to store actual name used, or NULL

error :

return location for a GError

Returns :

A file handle (as from open()) to the file opened for reading and writing. The file is opened in binary mode on platforms where there is a difference. The file handle should be closed with close(). In case of errors, -1 is returned and error will be set.

g_file_read_link ()

gchar *             g_file_read_link                    (const gchar *filename,
GError **error);

Reads the contents of the symbolic link filename like the POSIX readlink() function. The returned string is in the encoding used for filenames. Use g_filename_to_utf8() to convert it to UTF-8.

filename :

the symbolic link

error :

return location for a GError

Returns :

A newly-allocated string with the contents of the symbolic link, or NULL if an error occurred.

Since 2.4


g_mkdir_with_parents ()

int                 g_mkdir_with_parents                (const gchar *pathname,
int mode);

Create a directory if it doesn't already exist. Create intermediate parent directories as needed, too.

pathname :

a pathname in the GLib file name encoding

mode :

permissions to use for newly created directories

Returns :

0 if the directory already exists, or was successfully created. Returns -1 if an error occurred, with errno set.

Since 2.8


GDir

typedef struct _GDir GDir;

An opaque structure representing an opened directory.


g_dir_open ()

GDir *              g_dir_open                          (const gchar *path,
guint flags,
GError **error);

Opens a directory for reading. The names of the files in the directory can then be retrieved using g_dir_read_name().

path :

the path to the directory you are interested in. On Unix in the on-disk encoding. On Windows in UTF-8

flags :

Currently must be set to 0. Reserved for future use.

error :

return location for a GError, or NULL. If non-NULL, an error will be set if and only if g_dir_open() fails.

Returns :

a newly allocated GDir on success, NULL on failure. If non-NULL, you must free the result with g_dir_close() when you are finished with it.

g_dir_read_name ()

const gchar *       g_dir_read_name                     (GDir *dir);

Retrieves the name of the next entry in the directory. The '.' and '..' entries are omitted. On Windows, the returned name is in UTF-8. On Unix, it is in the on-disk encoding.

dir :

a GDir* created by g_dir_open()

Returns :

The entry's name or NULL if there are no more entries. The return value is owned by GLib and must not be modified or freed.

g_dir_rewind ()

void                g_dir_rewind                        (GDir *dir);

Resets the given directory. The next call to g_dir_read_name() will return the first entry again.

dir :

a GDir* created by g_dir_open()

g_dir_close ()

void                g_dir_close                         (GDir *dir);

Closes the directory and deallocates all related resources.

dir :

a GDir* created by g_dir_open()

GMappedFile

typedef struct _GMappedFile GMappedFile;

The GMappedFile represents a file mapping created with g_mapped_file_new(). It has only private members and should not be accessed directly.


g_mapped_file_new ()

GMappedFile *       g_mapped_file_new                   (const gchar *filename,
gboolean writable,
GError **error);

Maps a file into memory. On UNIX, this is using the mmap() function.

If writable is TRUE, the mapped buffer may be modified, otherwise it is an error to modify the mapped buffer. Modifications to the buffer are not visible to other processes mapping the same file, and are not written back to the file.

Note that modifications of the underlying file might affect the contents of the GMappedFile. Therefore, mapping should only be used if the file will not be modified, or if all modifications of the file are done atomically (e.g. using g_file_set_contents()).

filename :

The path of the file to load, in the GLib filename encoding

writable :

whether the mapping should be writable

error :

return location for a GError, or NULL

Returns :

a newly allocated GMappedFile which must be unref'd with g_mapped_file_unref(), or NULL if the mapping failed.

Since 2.8


g_mapped_file_ref ()

GMappedFile *       g_mapped_file_ref                   (GMappedFile *file);

Increments the reference count of file by one. It is safe to call this function from any thread.

file :

a GMappedFile

Returns :

the passed in GMappedFile.

Since 2.22


g_mapped_file_unref ()

void                g_mapped_file_unref                 (GMappedFile *file);

Decrements the reference count of file by one. If the reference count drops to 0, unmaps the buffer of file and frees it.

It is safe to call this function from any thread.

Since 2.22

file :

a GMappedFile

g_mapped_file_free ()

void                g_mapped_file_free                  (GMappedFile *file);

Warning

g_mapped_file_free has been deprecated since version 2.22 and should not be used in newly-written code. Use g_mapped_file_unref() instead.

This call existed before GMappedFile had refcounting and is currently exactly the same as g_mapped_file_unref().

file :

a GMappedFile

Since 2.8


g_mapped_file_get_length ()

gsize               g_mapped_file_get_length            (GMappedFile *file);

Returns the length of the contents of a GMappedFile.

file :

a GMappedFile

Returns :

the length of the contents of file.

Since 2.8


g_mapped_file_get_contents ()

gchar *             g_mapped_file_get_contents          (GMappedFile *file);

Returns the contents of a GMappedFile.

Note that the contents may not be zero-terminated, even if the GMappedFile is backed by a text file.

If the file is empty then NULL is returned.

file :

a GMappedFile

Returns :

the contents of file, or NULL.

Since 2.8


g_open ()

int                 g_open                              (const gchar *filename,
int flags,
int mode);

A wrapper for the POSIX open() function. The open() function is used to convert a pathname into a file descriptor.

On POSIX systems file descriptors are implemented by the operating system. On Windows, it's the C library that implements open() and file descriptors. The actual Win32 API for opening files is quite different, see MSDN documentation for CreateFile(). The Win32 API uses file handles, which are more randomish integers, not small integers like file descriptors.

Because file descriptors are specific to the C library on Windows, the file descriptor returned by this function makes sense only to functions in the same C library. Thus if the GLib-using code uses a different C library than GLib does, the file descriptor returned by this function cannot be passed to C library functions like write() or read().

See your C library manual for more details about open().

filename :

a pathname in the GLib file name encoding (UTF-8 on Windows)

flags :

as in open()

mode :

as in open()

Returns :

a new file descriptor, or -1 if an error occurred. The return value can be used exactly like the return value from open().

Since 2.6


g_rename ()

int                 g_rename                            (const gchar *oldfilename,
const gchar *newfilename);

A wrapper for the POSIX rename() function. The rename() function renames a file, moving it between directories if required.

See your C library manual for more details about how rename() works on your system. It is not possible in general on Windows to rename a file that is open to some process.

oldfilename :

a pathname in the GLib file name encoding (UTF-8 on Windows)

newfilename :

a pathname in the GLib file name encoding

Returns :

0 if the renaming succeeded, -1 if an error occurred

Since 2.6


g_mkdir ()

int                 g_mkdir                             (const gchar *filename,
int mode);

可移植作業系統介面(POSIX)的mkdir()外覆函式,mkdir()函式嘗試用給定的名稱及權限來建立目錄,mode參數在Windows裡會被忽略引數 。

查你的C函式庫手冊更多的mkdir()資訊。

filename :

GLib檔案名稱編碼的路徑名稱(在Windows用UTF-8)

mode :

使用最新建立的目錄的權限

Returns :

假如目錄被建立傳回0,假如有錯誤發生傳回-1

Since 2.6


g_stat ()

int                 g_stat                              (const gchar *filename,
struct _g_stat_struct *buf);

A wrapper for the POSIX stat() function. The stat() function returns information about a file. On Windows the stat() function in the C library checks only the FAT-style READONLY attribute and does not look at the ACL at all. Thus on Windows the protection bits in the st_mode field are a fabrication of little use.

See your C library manual for more details about stat().

filename :

a pathname in the GLib file name encoding (UTF-8 on Windows)

buf :

a pointer to a stat struct, which will be filled with the file information

Returns :

0 if the information was successfully retrieved, -1 if an error occurred

Since 2.6


g_lstat ()

int                 g_lstat                             (const gchar *filename,
struct _g_stat_struct *buf);

A wrapper for the POSIX lstat() function. The lstat() function is like stat() except that in the case of symbolic links, it returns information about the symbolic link itself and not the file that it refers to. If the system does not support symbolic links g_lstat() is identical to g_stat().

See your C library manual for more details about lstat().

filename :

a pathname in the GLib file name encoding (UTF-8 on Windows)

buf :

a pointer to a stat struct, which will be filled with the file information

Returns :

0 if the information was successfully retrieved, -1 if an error occurred

Since 2.6


g_unlink ()

int                 g_unlink                            (const gchar *filename);

A wrapper for the POSIX unlink() function. The unlink() function deletes a name from the filesystem. If this was the last link to the file and no processes have it opened, the diskspace occupied by the file is freed.

See your C library manual for more details about unlink(). Note that on Windows, it is in general not possible to delete files that are open to some process, or mapped into memory.

filename :

a pathname in the GLib file name encoding (UTF-8 on Windows)

Returns :

0 if the name was successfully deleted, -1 if an error occurred

Since 2.6


g_remove ()

int                 g_remove                            (const gchar *filename);

A wrapper for the POSIX remove() function. The remove() function deletes a name from the filesystem.

See your C library manual for more details about how remove() works on your system. On Unix, remove() removes also directories, as it calls unlink() for files and rmdir() for directories. On Windows, although remove() in the C library only works for files, this function tries first remove() and then if that fails rmdir(), and thus works for both files and directories. Note however, that on Windows, it is in general not possible to remove a file that is open to some process, or mapped into memory.

If this function fails on Windows you can't infer too much from the errno value. rmdir() is tried regardless of what caused remove() to fail. Any errno value set by remove() will be overwritten by that set by rmdir().

filename :

a pathname in the GLib file name encoding (UTF-8 on Windows)

Returns :

0 if the file was successfully removed, -1 if an error occurred

Since 2.6


g_rmdir ()

int                 g_rmdir                             (const gchar *filename);

A wrapper for the POSIX rmdir() function. The rmdir() function deletes a directory from the filesystem.

See your C library manual for more details about how rmdir() works on your system.

filename :

a pathname in the GLib file name encoding (UTF-8 on Windows)

Returns :

0 if the directory was successfully removed, -1 if an error occurred

Since 2.6


g_fopen ()

FILE *              g_fopen                             (const gchar *filename,
const gchar *mode);

A wrapper for the stdio fopen() function. The fopen() function opens a file and associates a new stream with it.

Because file descriptors are specific to the C library on Windows, and a file descriptor is partof the FILE struct, the FILE pointer returned by this function makes sense only to functions in the same C library. Thus if the GLib-using code uses a different C library than GLib does, the FILE pointer returned by this function cannot be passed to C library functions like fprintf() or fread().

See your C library manual for more details about fopen().

filename :

a pathname in the GLib file name encoding (UTF-8 on Windows)

mode :

a string describing the mode in which the file should be opened

Returns :

A FILE pointer if the file was successfully opened, or NULL if an error occurred

Since 2.6


g_freopen ()

FILE *              g_freopen                           (const gchar *filename,
const gchar *mode,
FILE *stream);

A wrapper for the POSIX freopen() function. The freopen() function opens a file and associates it with an existing stream.

See your C library manual for more details about freopen().

filename :

a pathname in the GLib file name encoding (UTF-8 on Windows)

mode :

a string describing the mode in which the file should be opened

stream :

an existing stream which will be reused, or NULL

Returns :

A FILE pointer if the file was successfully opened, or NULL if an error occurred.

Since 2.6


g_chmod ()

int                 g_chmod                             (const gchar *filename,
int mode);

A wrapper for the POSIX chmod() function. The chmod() function is used to set the permissions of a file system object.

On Windows the file protection mechanism is not at all POSIX-like, and the underlying chmod() function in the C library just sets or clears the FAT-style READONLY attribute. It does not touch any ACL. Software that needs to manage file permissions on Windows exactly should use the Win32 API.

See your C library manual for more details about chmod().

filename :

a pathname in the GLib file name encoding (UTF-8 on Windows)

mode :

as in chmod()

Returns :

zero if the operation succeeded, -1 on error.

Since 2.8


g_access ()

int                 g_access                            (const gchar *filename,
int mode);

A wrapper for the POSIX access() function. This function is used to test a pathname for one or several of read, write or execute permissions, or just existence.

On Windows, the file protection mechanism is not at all POSIX-like, and the underlying function in the C library only checks the FAT-style READONLY attribute, and does not look at the ACL of a file at all. This function is this in practise almost useless on Windows. Software that needs to handle file permissions on Windows more exactly should use the Win32 API.

See your C library manual for more details about access().

filename :

a pathname in the GLib file name encoding (UTF-8 on Windows)

mode :

as in access()

Returns :

zero if the pathname refers to an existing file system object that has all the tested permissions, or -1 otherwise or on error.

Since 2.8


g_creat ()

int                 g_creat                             (const gchar *filename,
int mode);

A wrapper for the POSIX creat() function. The creat() function is used to convert a pathname into a file descriptor, creating a file if necessary.

On POSIX systems file descriptors are implemented by the operating system. On Windows, it's the C library that implements creat() and file descriptors. The actual Windows API for opening files is different, see MSDN documentation for CreateFile(). The Win32 API uses file handles, which are more randomish integers, not small integers like file descriptors.

Because file descriptors are specific to the C library on Windows, the file descriptor returned by this function makes sense only to functions in the same C library. Thus if the GLib-using code uses a different C library than GLib does, the file descriptor returned by this function cannot be passed to C library functions like write() or read().

See your C library manual for more details about creat().

filename :

a pathname in the GLib file name encoding (UTF-8 on Windows)

mode :

as in creat()

Returns :

a new file descriptor, or -1 if an error occurred. The return value can be used exactly like the return value from creat().

Since 2.8


g_chdir ()

int                 g_chdir                             (const gchar *path);

A wrapper for the POSIX chdir() function. The function changes the current directory of the process to path.

See your C library manual for more details about chdir().

path :

a pathname in the GLib file name encoding (UTF-8 on Windows)

Returns :

0 on success, -1 if an error occurred.

Since 2.8


g_utime ()

int                 g_utime                             (const gchar *filename,
struct utimbuf *utb);

A wrapper for the POSIX utime() function. The utime() function sets the access and modification timestamps of a file.

See your C library manual for more details about how utime() works on your system.

filename :

a pathname in the GLib file name encoding (UTF-8 on Windows)

utb :

a pointer to a struct utimbuf.

Returns :

0 if the operation was successful, -1 if an error occurred

Since 2.18

Commandline option parser

Commandline option parser — parses commandline options

 

Synopsis

#include <glib.h>

enum                GOptionError;
#define             G_OPTION_ERROR
gboolean            (*GOptionArgFunc)                   (const gchar *option_name,
                                                         const gchar *value,
                                                         gpointer data,
                                                         GError **error);
                    GOptionContext;
GOptionContext *    g_option_context_new                (const gchar *parameter_string);
void                g_option_context_set_summary        (GOptionContext *context,
                                                         const gchar *summary);
const gchar *       g_option_context_get_summary        (GOptionContext *context);
void                g_option_context_set_description    (GOptionContext *context,
                                                         const gchar *description);
const gchar *       g_option_context_get_description    (GOptionContext *context);
const gchar *       (*GTranslateFunc)                   (const gchar *str,
                                                         gpointer data);
void                g_option_context_set_translate_func (GOptionContext *context,
                                                         GTranslateFunc func,
                                                         gpointer data,
                                                         GDestroyNotify destroy_notify);
void                g_option_context_set_translation_domain
                                                        (GOptionContext *context,
                                                         const gchar *domain);
void                g_option_context_free               (GOptionContext *context);
gboolean            g_option_context_parse              (GOptionContext *context,
                                                         gint *argc,
                                                         gchar ***argv,
                                                         GError **error);
void                g_option_context_set_help_enabled   (GOptionContext *context,
                                                         gboolean help_enabled);
gboolean            g_option_context_get_help_enabled   (GOptionContext *context);
void                g_option_context_set_ignore_unknown_options
                                                        (GOptionContext *context,
                                                         gboolean ignore_unknown);
gboolean            g_option_context_get_ignore_unknown_options
                                                        (GOptionContext *context);
gchar *             g_option_context_get_help           (GOptionContext *context,
                                                         gboolean main_help,
                                                         GOptionGroup *group);
enum                GOptionArg;
enum                GOptionFlags;
#define             G_OPTION_REMAINING
                    GOptionEntry;
void                g_option_context_add_main_entries   (GOptionContext *context,
                                                         const GOptionEntry *entries,
                                                         const gchar *translation_domain);
                    GOptionGroup;
void                g_option_context_add_group          (GOptionContext *context,
                                                         GOptionGroup *group);
void                g_option_context_set_main_group     (GOptionContext *context,
                                                         GOptionGroup *group);
GOptionGroup *      g_option_context_get_main_group     (GOptionContext *context);
GOptionGroup *      g_option_group_new                  (const gchar *name,
                                                         const gchar *description,
                                                         const gchar *help_description,
                                                         gpointer user_data,
                                                         GDestroyNotify destroy);
void                g_option_group_free                 (GOptionGroup *group);
void                g_option_group_add_entries          (GOptionGroup *group,
                                                         const GOptionEntry *entries);
gboolean            (*GOptionParseFunc)                 (GOptionContext *context,
                                                         GOptionGroup *group,
                                                         gpointer data,
                                                         GError **error);
void                g_option_group_set_parse_hooks      (GOptionGroup *group,
                                                         GOptionParseFunc pre_parse_func,
                                                         GOptionParseFunc post_parse_func);
void                (*GOptionErrorFunc)                 (GOptionContext *context,
                                                         GOptionGroup *group,
                                                         gpointer data,
                                                         GError **error);
void                g_option_group_set_error_hook       (GOptionGroup *group,
                                                         GOptionErrorFunc error_func);
void                g_option_group_set_translate_func   (GOptionGroup *group,
                                                         GTranslateFunc func,
                                                         gpointer data,
                                                         GDestroyNotify destroy_notify);
void                g_option_group_set_translation_domain
                                                        (GOptionGroup *group,
                                                         const gchar *domain);

Description

The GOption commandline parser is intended to be a simpler replacement for the popt library. It supports short and long commandline options, as shown in the following example:

testtreemodel -r 1 --max-size 20 --rand --display=:1.0 -vb -- file1 file2

The example demonstrates a number of features of the GOption commandline parser

  • Options can be single letters, prefixed by a single dash. Multiple short options can be grouped behind a single dash.

  • Long options are prefixed by two consecutive dashes.

  • Options can have an extra argument, which can be a number, a string or a filename. For long options, the extra argument can be appended with an equals sign after the option name, which is useful if the extra argument starts with a dash, which would otherwise cause it to be interpreted as another option.

  • Non-option arguments are returned to the application as rest arguments.

  • An argument consisting solely of two dashes turns off further parsing, any remaining arguments (even those starting with a dash) are returned to the application as rest arguments.

 

Another important feature of GOption is that it can automatically generate nicely formatted help output. Unless it is explicitly turned off with g_option_context_set_help_enabled(), GOption will recognize the --help, -?, --help-all and --help-groupname options (where groupname is the name of a GOptionGroup) and write a text similar to the one shown in the following example to stdout.

 

Usage:
  testtreemodel [OPTION...] - test tree model performance
 
Help Options:
  -h, --help               Show help options
  --help-all               Show all help options
  --help-gtk               Show GTK+ Options
 
Application Options:
  -r, --repeats=N          Average over N repetitions
  -m, --max-size=M         Test up to 2^M items
  --display=DISPLAY        X display to use
  -v, --verbose            Be verbose
  -b, --beep               Beep when done   
  --rand                   Randomize the data

 

GOption groups options in GOptionGroups, which makes it easy to incorporate options from multiple sources. The intended use for this is to let applications collect option groups from the libraries it uses, add them to their GOptionContext, and parse all options by a single call to g_option_context_parse(). See gtk_get_option_group() for an example.

If an option is declared to be of type string or filename, GOption takes care of converting it to the right encoding; strings are returned in UTF-8, filenames are returned in the GLib filename encoding. Note that this only works if setlocale() has been called before g_option_context_parse().

Here is a complete example of setting up GOption to parse the example commandline above and produce the example help output.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
static gint repeats = 2;
static gint max_size = 8;
static gboolean verbose = FALSE;
static gboolean beep = FALSE;
static gboolean rand = FALSE;

static GOptionEntry entries[] = 
{
  { "repeats", 'r', 0, G_OPTION_ARG_INT, &repeats, "Average over N repetitions", "N" },
  { "max-size", 'm', 0, G_OPTION_ARG_INT, &max_size, "Test up to 2^M items", "M" },
  { "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, "Be verbose", NULL },
  { "beep", 'b', 0, G_OPTION_ARG_NONE, &beep, "Beep when done", NULL },
  { "rand", 0, 0, G_OPTION_ARG_NONE, &rand, "Randomize the data", NULL },
  { NULL }
};

int 
main (int argc, char *argv[])
{
  GError *error = NULL;
  GOptionContext *context;

  context = g_option_context_new ("- test tree model performance");
  g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
  g_option_context_add_group (context, gtk_get_option_group (TRUE));
  if (!g_option_context_parse (context, &argc, &argv, &error))
    {
      g_print ("option parsing failed: %s\n", error->message);
      exit (1);
    }

  // ...

}

 

Details

enum GOptionError

typedef enum
{
  G_OPTION_ERROR_UNKNOWN_OPTION,
  G_OPTION_ERROR_BAD_VALUE,
  G_OPTION_ERROR_FAILED
} GOptionError;

Error codes returned by option parsing.

G_OPTION_ERROR_UNKNOWN_OPTION

An option was not known to the parser. This error will only be reported, if the parser hasn't been instructed to ignore unknown options, see g_option_context_set_ignore_unknown_options().

G_OPTION_ERROR_BAD_VALUE

A value couldn't be parsed.

G_OPTION_ERROR_FAILED

A GOptionArgFunc callback failed.

G_OPTION_ERROR

#define G_OPTION_ERROR (g_option_error_quark ())

Error domain for option parsing. Errors in this domain will be from the GOptionError enumeration. See GError for information on error domains.


GOptionArgFunc ()

gboolean            (*GOptionArgFunc)                   (const gchar *option_name,
                                                         const gchar *value,
                                                         gpointer data,
                                                         GError **error);

The type of function to be passed as callback for G_OPTION_ARG_CALLBACK options.

option_name :

The name of the option being parsed. This will be either a single dash followed by a single letter (for a short name) or two dashes followed by a long option name.

value :

The value to be parsed.

data :

User data added to the GOptionGroup containing the option when it was created with g_option_group_new()

error :

A return location for errors. The error code G_OPTION_ERROR_FAILED is intended to be used for errors in GOptionArgFunc callbacks.

Returns :

TRUE if the option was successfully parsed, FALSE if an error occurred, in which case error should be set with g_set_error()

GOptionContext

typedef struct _GOptionContext GOptionContext;

GOptionContext結構定義命令列參數剖析器能接受的參數,這個結構只有私有欄位,不應該直接存取。


g_option_context_new ()

GOptionContext *    g_option_context_new                (const gchar *parameter_string);

新增一個新的選項內容。

parameter_string 有很多目標,它可以用來新增"rest"參數的敘述,這個敘述不會被GOptionContext解析,通常會像這樣"FILES" 或"FILE1 FILE2...",假如你正使用 G_OPTION_REMAINING 來收集"rest"參數,GLib會在使用說明裡藉著使用相關的GOptionEntry arg_description 來自動處理。

另一種用法是給一個程式功能的簡短總結,像" - frob the strings",這將顯示在用法的同一行,對於程式功能較長的敘述就會以段落來顯示在用法的下方,使用g_option_context_set_summary()

注意parameter_string 使用有g_option_context_set_translate_func()程式集來翻譯,所以一般不會通過翻譯。

parameter_string :

一個用來顯示在--help輸出的第一行的字串,在使用總結programname [OPTION...]之後

傳回

一個新建的GOptionContext,,在使用後用g_option_context_free() 釋放。

Since 2.6


g_option_context_set_summary ()

void                g_option_context_set_summary        (GOptionContext *context,
                                                         const gchar *summary);

Adds a string to be displayed in --help output before the list of options. This is typically a summary of the program functionality.

Note that the summary is translated (see g_option_context_set_translate_func() and g_option_context_set_translation_domain()).

context :

a GOptionContext

summary :

a string to be shown in --help output before the list of options, or NULL

Since 2.12


g_option_context_get_summary ()

const gchar *       g_option_context_get_summary        (GOptionContext *context);

Returns the summary. See g_option_context_set_summary().

context :

a GOptionContext

Returns :

the summary

Since 2.12


g_option_context_set_description ()

void                g_option_context_set_description    (GOptionContext *context,
                                                         const gchar *description);

Adds a string to be displayed in --help output after the list of options. This text often includes a bug reporting address.

Note that the summary is translated (see g_option_context_set_translate_func()).

context :

a GOptionContext

description :

a string to be shown in --help output after the list of options, or NULL

Since 2.12


g_option_context_get_description ()

const gchar *       g_option_context_get_description    (GOptionContext *context);

Returns the description. See g_option_context_set_description().

context :

a GOptionContext

Returns :

the description

Since 2.12


GTranslateFunc ()

const gchar *       (*GTranslateFunc)                   (const gchar *str,
                                                         gpointer data);

The type of functions which are used to translate user-visible strings, for --help output.

str :

the untranslated string

data :

user data specified when installing the function, e.g. in g_option_group_set_translate_func()

Returns :

a translation of the string for the current locale. The returned string is owned by GLib and must not be freed.

g_option_context_set_translate_func ()

void                g_option_context_set_translate_func (GOptionContext *context,
                                                         GTranslateFunc func,
                                                         gpointer data,
                                                         GDestroyNotify destroy_notify);

Sets the function which is used to translate the contexts user-visible strings, for --help output. If func is NULL, strings are not translated.

Note that option groups have their own translation functions, this function only affects the parameter_string (see g_option_context_new()), the summary (see g_option_context_set_summary()) and the description (see g_option_context_set_description()).

If you are using gettext(), you only need to set the translation domain, see g_option_context_set_translation_domain().

context :

a GOptionContext

func :

the GTranslateFunc, or NULL

data :

user data to pass to func, or NULL

destroy_notify :

a function which gets called to free data, or NULL

Since 2.12


g_option_context_set_translation_domain ()

void                g_option_context_set_translation_domain
                                                        (GOptionContext *context,
                                                         const gchar *domain);

A convenience function to use gettext() for translating user-visible strings.

context :

a GOptionContext

domain :

the domain to use

Since 2.12


g_option_context_free ()

void                g_option_context_free               (GOptionContext *context);

Frees context and all the groups which have been added to it.

Please note that parsed arguments need to be freed separately (see GOptionEntry).

context :

a GOptionContext

Since 2.6


g_option_context_parse ()

gboolean            g_option_context_parse              (GOptionContext *context,
                                                         gint *argc,
                                                         gchar ***argv,
                                                         GError **error);

Parses the command line arguments, recognizing options which have been added to context. A side-effect of calling this function is that g_set_prgname() will be called.

If the parsing is successful, any parsed arguments are removed from the array and argc and argv are updated accordingly. A '--' option is stripped from argv unless there are unparsed options before and after it, or some of the options after it start with '-'. In case of an error, argc and argv are left unmodified.

If automatic --help support is enabled (see g_option_context_set_help_enabled()), and the argv array contains one of the recognized help options, this function will produce help output to stdout and call exit (0).

Note that function depends on the current locale for automatic character set conversion of string and filename arguments.

context :

a GOptionContext

argc :

a pointer to the number of command line arguments

argv :

a pointer to the array of command line arguments

error :

a return location for errors

Returns :

TRUE if the parsing was successful, FALSE if an error occurred

Since 2.6


g_option_context_set_help_enabled ()

void                g_option_context_set_help_enabled   (GOptionContext *context,
                                                         gboolean help_enabled);

Enables or disables automatic generation of --help output. By default, g_option_context_parse() recognizes --help, -h, -?, --help-all and --help-groupname and creates suitable output to stdout.

context :

a GOptionContext

help_enabled :

TRUE to enable --help, FALSE to disable it

Since 2.6


g_option_context_get_help_enabled ()

gboolean            g_option_context_get_help_enabled   (GOptionContext *context);

Returns whether automatic --help generation is turned on for context. See g_option_context_set_help_enabled().

context :

a GOptionContext

Returns :

TRUE if automatic help generation is turned on.

Since 2.6


g_option_context_set_ignore_unknown_options ()

void                g_option_context_set_ignore_unknown_options
                                                        (GOptionContext *context,
                                                         gboolean ignore_unknown);

Sets whether to ignore unknown options or not. If an argument is ignored, it is left in the argv array after parsing. By default, g_option_context_parse() treats unknown options as error.

This setting does not affect non-option arguments (i.e. arguments which don't start with a dash). But note that GOption cannot reliably determine whether a non-option belongs to a preceding unknown option.

context :

a GOptionContext

ignore_unknown :

TRUE to ignore unknown options, FALSE to produce an error when unknown options are met

Since 2.6


g_option_context_get_ignore_unknown_options ()

gboolean            g_option_context_get_ignore_unknown_options
                                                        (GOptionContext *context);

Returns whether unknown options are ignored or not. See g_option_context_set_ignore_unknown_options().

context :

a GOptionContext

Returns :

TRUE if unknown options are ignored.

Since 2.6


g_option_context_get_help ()

gchar *             g_option_context_get_help           (GOptionContext *context,
                                                         gboolean main_help,
                                                         GOptionGroup *group);

Returns a formatted, translated help text for the given context. To obtain the text produced by --help, call g_option_context_get_help (context, TRUE, NULL). To obtain the text produced by --help-all, call g_option_context_get_help (context, FALSE, NULL). To obtain the help text for an option group, call g_option_context_get_help (context, FALSE, group).

context :

a GOptionContext

main_help :

if TRUE, only include the main group

group :

the GOptionGroup to create help for, or NULL

Returns :

A newly allocated string containing the help text

Since 2.14


enum GOptionArg

typedef enum
{
  G_OPTION_ARG_NONE,
  G_OPTION_ARG_STRING,
  G_OPTION_ARG_INT,
  G_OPTION_ARG_CALLBACK,
  G_OPTION_ARG_FILENAME,
  G_OPTION_ARG_STRING_ARRAY,
  G_OPTION_ARG_FILENAME_ARRAY,
  G_OPTION_ARG_DOUBLE,
  G_OPTION_ARG_INT64
} GOptionArg;

The GOptionArg enum values determine which type of extra argument the options expect to find. If an option expects an extra argument, it can be specified in several ways; with a short option: -x arg, with a long option: --name arg or combined in a single argument: --name=arg.

G_OPTION_ARG_NONE

No extra argument. This is useful for simple flags.

G_OPTION_ARG_STRING

The option takes a string argument.

G_OPTION_ARG_INT

The option takes an integer argument.

G_OPTION_ARG_CALLBACK

The option provides a callback to parse the extra argument.

G_OPTION_ARG_FILENAME

The option takes a filename as argument.

G_OPTION_ARG_STRING_ARRAY

The option takes a string argument, multiple uses of the option are collected into an array of strings.

G_OPTION_ARG_FILENAME_ARRAY

The option takes a filename as argument, multiple uses of the option are collected into an array of strings.

G_OPTION_ARG_DOUBLE

The option takes a double argument. The argument can be formatted either for the user's locale or for the "C" locale. Since 2.12

G_OPTION_ARG_INT64

The option takes a 64-bit integer. Like G_OPTION_ARG_INT but for larger numbers. The number can be in decimal base, or in hexadecimal (when prefixed with 0x, for example, 0xffffffff). Since 2.12

enum GOptionFlags

typedef enum
{
  G_OPTION_FLAG_HIDDEN		= 1 << 0,
  G_OPTION_FLAG_IN_MAIN		= 1 << 1,
  G_OPTION_FLAG_REVERSE		= 1 << 2,
  G_OPTION_FLAG_NO_ARG		= 1 << 3,
  G_OPTION_FLAG_FILENAME = 1 << 4,
  G_OPTION_FLAG_OPTIONAL_ARG    = 1 << 5,
  G_OPTION_FLAG_NOALIAS	        = 1 << 6
} GOptionFlags;

Flags which modify individual options.

G_OPTION_FLAG_HIDDEN

The option doesn't appear in --help output.

G_OPTION_FLAG_IN_MAIN

The option appears in the main section of the --help output, even if it is defined in a group.

G_OPTION_FLAG_REVERSE

For options of the G_OPTION_ARG_NONE kind, this flag indicates that the sense of the option is reversed.

G_OPTION_FLAG_NO_ARG

For options of the G_OPTION_ARG_CALLBACK kind, this flag indicates that the callback does not take any argument (like a G_OPTION_ARG_NONE option). Since 2.8

G_OPTION_FLAG_FILENAME

For options of the G_OPTION_ARG_CALLBACK kind, this flag indicates that the argument should be passed to the callback in the GLib filename encoding rather than UTF-8. Since 2.8

G_OPTION_FLAG_OPTIONAL_ARG

For options of the G_OPTION_ARG_CALLBACK kind, this flag indicates that the argument supply is optional. If no argument is given then data of GOptionParseFunc will be set to NULL. Since 2.8

G_OPTION_FLAG_NOALIAS

This flag turns off the automatic conflict resolution which prefixes long option names with groupname- if there is a conflict. This option should only be used in situations where aliasing is necessary to model some legacy commandline interface. It is not safe to use this option, unless all option groups are under your direct control. Since 2.8.

G_OPTION_REMAINING

#define G_OPTION_REMAINING ""

If a long option in the main group has this name, it is not treated as a regular option. Instead it collects all non-option arguments which would otherwise be left in argv. The option must be of type G_OPTION_ARG_CALLBACK, G_OPTION_ARG_STRING_ARRAY or G_OPTION_ARG_FILENAME_ARRAY.

Using G_OPTION_REMAINING instead of simply scanning argv for leftover arguments has the advantage that GOption takes care of necessary encoding conversions for strings or filenames.

Since 2.6


GOptionEntry

typedef struct {
  const gchar *long_name;
  gchar        short_name;
  gint         flags;

  GOptionArg   arg;
  gpointer     arg_data;
  
  const gchar *description;
  const gchar *arg_description;
} GOptionEntry;

A GOptionEntry defines a single option. To have an effect, they must be added to a GOptionGroup with g_option_context_add_main_entries() or g_option_group_add_entries().

const gchar *long_name;

The long name of an option can be used to specify it in a commandline as --long_name. Every option must have a long name. To resolve conflicts if multiple option groups contain the same long name, it is also possible to specify the option as --groupname-long_name.

gchar short_name;

If an option has a short name, it can be specified -short_name in a commandline. short_name must be a printable ASCII character different from '-', or zero if the option has no short name.

gint flags;

Flags from GOptionFlags.

GOptionArg arg;

The type of the option, as a GOptionArg.

gpointer arg_data;

If the arg type is G_OPTION_ARG_CALLBACK, then arg_data must point to a GOptionArgFunc callback function, which will be called to handle the extra argument. Otherwise, arg_data is a pointer to a location to store the value, the required type of the location depends on the arg type: If arg type is G_OPTION_ARG_STRING or G_OPTION_ARG_FILENAME the location will contain a newly allocated string if the option was given. That string needs to be freed by the callee using g_free(). Likewise if arg type is G_OPTION_ARG_STRING_ARRAY or G_OPTION_ARG_FILENAME_ARRAY, the data should be freed using g_strfreev().

const gchar *description;

the description for the option in --help output. The description is translated using the translate_func of the group, see g_option_group_set_translation_domain().

const gchar *arg_description;

The placeholder to use for the extra argument parsed by the option in --help output. The arg_description is translated using the translate_func of the group, see g_option_group_set_translation_domain().

g_option_context_add_main_entries ()

void                g_option_context_add_main_entries   (GOptionContext *context,
                                                         const GOptionEntry *entries,
                                                         const gchar *translation_domain);

A convenience function which creates a main group if it doesn't exist, adds the entries to it and sets the translation domain.

context :

a GOptionContext

entries :

a NULL-terminated array of GOptionEntrys

translation_domain :

a translation domain to use for translating the --help output for the options in entries with gettext(), or NULL

Since 2.6


GOptionGroup

typedef struct _GOptionGroup GOptionGroup;

A GOptionGroup struct defines the options in a single group. The struct has only private fields and should not be directly accessed.

All options in a group share the same translation function. Libraries which need to parse commandline options are expected to provide a function for getting a GOptionGroup holding their options, which the application can then add to its GOptionContext.


g_option_context_add_group ()

void                g_option_context_add_group          (GOptionContext *context,
                                                         GOptionGroup *group);

Adds a GOptionGroup to the context, so that parsing with context will recognize the options in the group. Note that the group will be freed together with the context when g_option_context_free() is called, so you must not free the group yourself after adding it to a context.

context :

a GOptionContext

group :

the group to add

Since 2.6


g_option_context_set_main_group ()

void                g_option_context_set_main_group     (GOptionContext *context,
                                                         GOptionGroup *group);

Sets a GOptionGroup as main group of the context. This has the same effect as calling g_option_context_add_group(), the only difference is that the options in the main group are treated differently when generating --help output.

context :

a GOptionContext

group :

the group to set as main group

Since 2.6


g_option_context_get_main_group ()

GOptionGroup *      g_option_context_get_main_group     (GOptionContext *context);

Returns a pointer to the main group of context.

context :

a GOptionContext

Returns :

the main group of context, or NULL if context doesn't have a main group. Note that group belongs to context and should not be modified or freed.

Since 2.6


g_option_group_new ()

GOptionGroup *      g_option_group_new                  (const gchar *name,
                                                         const gchar *description,
                                                         const gchar *help_description,
                                                         gpointer user_data,
                                                         GDestroyNotify destroy);

Creates a new GOptionGroup.

name :

the name for the option group, this is used to provide help for the options in this group with --help-name

description :

a description for this group to be shown in --help. This string is translated using the translation domain or translation function of the group

help_description :

a description for the --help-name option. This string is translated using the translation domain or translation function of the group

user_data :

user data that will be passed to the pre- and post-parse hooks, the error hook and to callbacks of G_OPTION_ARG_CALLBACK options, or NULL

destroy :

a function that will be called to free user_data, or NULL

Returns :

a newly created option group. It should be added to a GOptionContext or freed with g_option_group_free().

Since 2.6


g_option_group_free ()

void                g_option_group_free                 (GOptionGroup *group);

Frees a GOptionGroup. Note that you must not free groups which have been added to a GOptionContext.

group :

a GOptionGroup

Since 2.6


g_option_group_add_entries ()

void                g_option_group_add_entries          (GOptionGroup *group,
                                                         const GOptionEntry *entries);

Adds the options specified in entries to group.

group :

a GOptionGroup

entries :

a NULL-terminated array of GOptionEntrys

Since 2.6


GOptionParseFunc ()

gboolean            (*GOptionParseFunc)                 (GOptionContext *context,
                                                         GOptionGroup *group,
                                                         gpointer data,
                                                         GError **error);

The type of function that can be called before and after parsing.

context :

The active GOptionContext

group :

The group to which the function belongs

data :

User data added to the GOptionGroup containing the option when it was created with g_option_group_new()

error :

A return location for error details

Returns :

TRUE if the function completed successfully, FALSE if an error occurred, in which case error should be set with g_set_error()

g_option_group_set_parse_hooks ()

void                g_option_group_set_parse_hooks      (GOptionGroup *group,
                                                         GOptionParseFunc pre_parse_func,
                                                         GOptionParseFunc post_parse_func);

Associates two functions with group which will be called from g_option_context_parse() before the first option is parsed and after the last option has been parsed, respectively.

Note that the user data to be passed to pre_parse_func and post_parse_func can be specified when constructing the group with g_option_group_new().

group :

a GOptionGroup

pre_parse_func :

a function to call before parsing, or NULL

post_parse_func :

a function to call after parsing, or NULL

Since 2.6


GOptionErrorFunc ()

void                (*GOptionErrorFunc)                 (GOptionContext *context,
                                                         GOptionGroup *group,
                                                         gpointer data,
                                                         GError **error);

The type of function to be used as callback when a parse error occurs.

context :

The active GOptionContext

group :

The group to which the function belongs

data :

User data added to the GOptionGroup containing the option when it was created with g_option_group_new()

error :

The GError containing details about the parse error

g_option_group_set_error_hook ()

void                g_option_group_set_error_hook       (GOptionGroup *group,
                                                         GOptionErrorFunc error_func);

Associates a function with group which will be called from g_option_context_parse() when an error occurs.

Note that the user data to be passed to error_func can be specified when constructing the group with g_option_group_new().

group :

a GOptionGroup

error_func :

a function to call when an error occurs

Since 2.6


g_option_group_set_translate_func ()

void                g_option_group_set_translate_func   (GOptionGroup *group,
                                                         GTranslateFunc func,
                                                         gpointer data,
                                                         GDestroyNotify destroy_notify);

Sets the function which is used to translate user-visible strings, for --help output. Different groups can use different GTranslateFuncs. If func is NULL, strings are not translated.

If you are using gettext(), you only need to set the translation domain, see g_option_group_set_translation_domain().

group :

a GOptionGroup

func :

the GTranslateFunc, or NULL

data :

user data to pass to func, or NULL

destroy_notify :

a function which gets called to free data, or NULL

Since 2.6


g_option_group_set_translation_domain ()

void                g_option_group_set_translation_domain
                                                        (GOptionGroup *group,
                                                         const gchar *domain);

A convenience function to use gettext() for translating user-visible strings.

group :

a GOptionGroup

domain :

the domain to use

Since 2.6