glib
简介
- 源码下载
- glib库是Linux平台下最常用的C语言函数库,它具有很好的可移植性和实用性
- 编译链接:gcc g_init.c pkg-config --libs --cflags glib-2.0 -o g_init
- 功能特色
(1)gobject是glib的精粹,gobject是所有类的基类。signal在其中也是一大特色。
(2)glib提供了动态数组、单/双向链表、哈希表、多叉树、平衡二叉树、字符串等常用容器,完全是面向对象设计的。
(3)glib里提供了词法分析、markup语言解析、ini文件存取等功能
(4)glib提供了一套跨平台的backtrace函数
(5)实现了一套完整的log机制
(6)glib提供了一些的手段定位内存问题 - GLib 实现了一个功能强大的事件循环分发处理机制.
(1)被抽象成 GMainLoop,用于循环处理事件源上的事件,每个 GMainLoop 都工作在指定的 GMainContext 上。
(2)事件源在 GLib 中则被抽象成了 GSource。在 GMainContext 中有一个 GSource 列表。
(3)GLib 内部定义实现了三种类型的事件源,分别是 Idle, Timeout 和 I/O。同时也支持创建自定义的事件源。
命令行参数解析
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
gboolean cmd_arg_show_version = FALSE;
gint cmd_arg_product = 0;
gchar *cmd_arg_name = NULL;
static GOptionEntry entries[] = {
{ "version", 'v', 0, G_OPTION_ARG_NONE, &cmd_arg_show_version, "Show version", NULL },
{ "product", 'p', 0, G_OPTION_ARG_INT, &cmd_arg_product, "product mode", NULL },
{ "name", 'n', 0, G_OPTION_ARG_STRING, &cmd_arg_name, "product name", NULL },
{ NULL }
};
typedef struct _glib_context {
GMainLoop *main_loop;
} glib_context_t;
static glib_context_t *glib_context = NULL;
static void sig_int_handler(int signo G_GNUC_UNUSED)
{
if (g_main_loop_is_running(glib_context->main_loop)) {
g_main_loop_quit(glib_context->main_loop);
}
}
int main(int argc, char *argv[])
{
GError *error = NULL;
GOptionContext *context = g_option_context_new("- argument");
g_option_context_add_main_entries(context, entries, NULL);
if (!g_option_context_parse(context, &argc, &argv, &error)) {
g_printerr("option parsing failed: %sn", error->message);
g_option_context_free(context);
exit(EXIT_FAILURE);
}
g_option_context_free(context);
if (cmd_arg_show_version) {
g_print("%sn", "v1.0");
exit(EXIT_SUCCESS);
}
if (cmd_arg_name) {
g_print("cmd_arg_name: %sn", cmd_arg_name);
exit(EXIT_SUCCESS);
}
glib_context = (glib_context_t *)g_malloc0(sizeof(glib_context_t));
glib_context->main_loop = g_main_loop_new(NULL, FALSE);
g_main_loop_run(glib_context->main_loop);
if (glib_context->main_loop) {
g_main_loop_unref(glib_context->main_loop);
glib_context->main_loop = NULL;
}
g_free(glib_context);
glib_context = NULL;
return 0;
}
事件源
- 事件源: Idle, Timeout, I/O 和 自定义的事件源
- 自定义事件源:将外部信号(事件)挂到程序中的指定主循环上,从而在 g_main_loop_run 中可以响应这些事件
(1)自定义的事件源继承 GSource 的结构体,即自定义事件源的结构体 的第一个成员是 GSource 结构体, 其后便可放置程序所需数据
(2)实现事件源所规定的接口,主要为 prepare, check, dispatch, finalize 等事件处理函数(回调函数),它们包含于 GSourceFuncs 结构体中
(3)sample: struct Test_Source { GSource _source; gchar userdata[256]; }