GString入門
glibで文字列扱う時は、g_strxxx ()みたいな関数を使えば良いと勝手に思ってたけど、GStringってのがあって、
typedef struct { gchar *str; gsize len; gsize allocated_len; } GString;
みたいな宣言がなされているみたい。
new ()、free ()でメモリ確保と解放したり、 append () prepend () insert () overwrite () erace () trancate () で編集したり、printfまで使えるみたい。
GStringはGObjectを継承してないので、g_type_init ()は不要ということで、newしてfreeするプログラムを書いてみた。
#include <glib.h> #include <glib/gprintf.h> gint main (gint argc, gchar* argv[]) { GString *gstr; gstr = g_string_new ("This is a pen."); g_printf ("%s\n", gstr->str); g_string_free (gstr, TRUE); return 0; }
ビルドと実行は以下の通り。
$ gcc gstring.c $(pkg-config --cflags --libs glib-2.0) $ ./a.out This is a pen.
gstr->strしているところは、*gstrでも問題ない(構造体の先頭要素)のですが、一応変更があったら怖いからこうしました。最近は、構造体の先頭にCountByte(サイズ)を入れるのが一般的になっているようです。