File: gtkfaq-8.html

package info (click to toggle)
gtk%2B1.2 1.2.10-18
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 14,468 kB
  • ctags: 12,966
  • sloc: ansic: 137,190; sh: 13,303; makefile: 1,170; perl: 328; awk: 274; lisp: 7
file content (413 lines) | stat: -rw-r--r-- 12,157 bytes parent folder | download | duplicates (4)
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML>
<HEAD>
 <META NAME="GENERATOR" CONTENT="LinuxDoc-Tools 0.9.21">
 <TITLE>GTK+ FAQ: About GLib</TITLE>
 <LINK HREF="gtkfaq-9.html" REL=next>
 <LINK HREF="gtkfaq-7.html" REL=previous>
 <LINK HREF="gtkfaq.html#toc8" REL=contents>
</HEAD>
<BODY BGCOLOR="#FFFFFF">
<A HREF="gtkfaq-9.html">Next</A>
<A HREF="gtkfaq-7.html">Previous</A>
<A HREF="gtkfaq.html#toc8">Contents</A>
<HR NOSHADE>
<H2><A NAME="s8">8.</A> <A HREF="gtkfaq.html#toc8">About GLib</A></H2>

<H2><A NAME="ss8.1">8.1</A> <A HREF="gtkfaq.html#toc8.1">What is GLib?</A>
</H2>

<P>GLib is a library of useful functions and definitions available for use 
when creating GDK and GTK applications. It provides replacements for some
standard libc functions, such as malloc, which are buggy on some systems.</P>
<P>It also provides routines for handling:
<UL>
<LI>Doubly Linked Lists</LI>
<LI>Singly Linked Lists</LI>
<LI>Timers</LI>
<LI>String Handling</LI>
<LI>A Lexical Scanner</LI>
<LI>Error Functions</LI>
</UL>
</P>

<H2><A NAME="ss8.2">8.2</A> <A HREF="gtkfaq.html#toc8.2">How can I use the doubly linked lists?</A>
</H2>

<P>The GList object is defined as:</P>
<P>
<BLOCKQUOTE><CODE>
<PRE>
typedef struct _GList GList;

struct _GList
{
  gpointer data;
  GList *next;
  GList *prev;
};
</PRE>
</CODE></BLOCKQUOTE>
</P>
<P>To use the GList objects, simply :</P>
<P>
<BLOCKQUOTE><CODE>
<PRE>
GList   *list = NULL;
GList   *listrunner;
gint    array[] = { 1, 2, 3, 4, 5, 6 };
gint    pos;
gint    *value;

/* add data to the list */
for (pos=0;pos &lt; sizeof array; pos++) {
  list = g_list_append(list, (gpointer)&amp;array[pos]);
}

/* run through the list */
listrunner = g_list_first(list);
while (listrunner) {
  value = (gint *)listrunner->data;
  printf("%d\n", *value);
  listrunner = g_list_next(listrunner);
}

/* removing datas from the list */
listrunner = g_list_first(list);
list = g_list_remove_link(list, listrunner);
list = g_list_remove(list, &amp;array[4]);
</PRE>
</CODE></BLOCKQUOTE>
</P>
<P>The same code is usable with singly linked lists (GSList objects) by replacing
g_list_* functions with the relevant g_slist_* ones (g_slist_append, 
g_slist_remove, ...). Just remember that since you can't go backward in a singly
linked list, there is no g_slist_first function - you'll need to keep a 
reference on the first node of the list.</P>


<H2><A NAME="ss8.3">8.3</A> <A HREF="gtkfaq.html#toc8.3">Memory does not seem to be released when I free the list nodes I've allocated</A>
</H2>

<P>GLib tries to be "intelligent" on this special issue: it assumes that
you are likely to reuse the objects, so caches the allocated memory.
If you do not want to use this behavior, you'll probably want to set
up a special allocator.</P>
<P>To quote Tim Janik:
<BLOCKQUOTE>
If you have a certain portion of code that uses *lots* of GLists or
GNodes, and you know you'd better want to release all of them after a
short while, you'd want to use a GAllocator. Pushing an allocator into
g_list will make all subsequent glist operations private to that
allocator's memory pool (and thus you have to take care to pop the
allocator again, before making any external calls):
</BLOCKQUOTE>
</P>
<P>
<BLOCKQUOTE><CODE>
<PRE>
GAllocator *allocator;
GList *list = NULL;
guint i;

/* set a new allocation pool for GList nodes */
allocator = g_allocator_new ("list heap", 1024);
g_list_push_allocator (allocator);

/* do some list operations */
for (i = 0; i &lt; 4096; i++)
  list = g_list_prepend (list, NULL);
list = g_list_reverse (list);

/* beware to pop allocator befor calling external functions */
g_list_pop_allocator ();
gtk_label_set_text (GTK_LABEL (some_label), "some text");

/* and set our private glist pool again */
g_list_push_allocator (allocator);

/* do some list operations */
g_list_free (list);
list = NULL;
for (i = 0; i &lt; 4096; i++)
  list = g_list_prepend (list, NULL);
  
/* and back out (while freeing all of the list nodes in our pool) */
g_list_pop_allocator ();
g_allocator_free (allocator);
</PRE>
</CODE></BLOCKQUOTE>
</P>

<H2><A NAME="ss8.4">8.4</A> <A HREF="gtkfaq.html#toc8.4">Why use g_print, g_malloc, g_strdup and fellow glib functions? </A>
</H2>

<P>Thanks to Tim Janik who wrote to gtk-list: (slightly modified)
<BLOCKQUOTE>
Regarding g_malloc(), g_free() and siblings, these functions are much
safer than their libc equivalents. For example, g_free() just returns
if called with NULL. Also, if USE_DMALLOC is defined, the definition
for these functions changes (in glib.h) to use MALLOC(), FREE() etc...
If MEM_PROFILE or MEM_CHECK are defined, there are even small
statistics made counting the used block sizes (shown by
g_mem_profile() / g_mem_check()).
<P>Considering the fact that glib provides an interface for memory chunks
to save space if you have lots of blocks that are always the same size
and to mark them ALLOC_ONLY if needed, it is just straight forward to
create a small saver (debug able) wrapper around the normal malloc/free
stuff as well - just like gdk covers Xlib. ;)</P>
<P>Using g_error() and g_warning() inside of applications like the GIMP
that fully rely on gtk even gives the opportunity to pop up a window
showing the messages inside of a gtk window with your own handler
(by using g_set_error_handler()) along the lines of <CODE>gtk_print()</CODE>
(inside of gtkmain.c).</P>
</BLOCKQUOTE>
</P>

<H2><A NAME="ss8.5">8.5</A> <A HREF="gtkfaq.html#toc8.5">What's a GScanner and how do I use one? </A>
</H2>

<P>A GScanner will tokenize your text, that is, it'll return an integer
for every word or number that appears in its input stream, following
certain (customizable) rules to perform this translation.
You still need to write the parsing functions on your own though.</P>
<P>Here's a little test program supplied by Tim Janik that will parse</P>
<P>
<PRE>
&lt;SYMBOL> = &lt;OPTIONAL-MINUS> &lt;NUMBER> ;
</PRE>
</P>
<P>constructs, while skipping "#\n" and "/**/" style comments.</P>
<P>
<PRE>
#include &lt;glib.h>

/* some test text to be fed into the scanner */
static const gchar *test_text =
( "ping = 5;\n"
  "/* slide in some \n"
  " * comments, just for the\n"
  " * fun of it \n"
  " */\n"
  "pong = -6; \n"
  "\n"
  "# the next value is a float\n"
  "zonk = 0.7;\n"
  "# redefine ping\n"
  "ping = - 0.5;\n" );

/* define enumeration values to be returned for specific symbols */
enum {
  SYMBOL_PING = G_TOKEN_LAST + 1,
  SYMBOL_PONG = G_TOKEN_LAST + 2,
  SYMBOL_ZONK = G_TOKEN_LAST + 3
};

/* symbol array */
static const struct {
  gchar *symbol_name;
  guint  symbol_token;
} symbols[] = {
  { "ping", SYMBOL_PING, },
  { "pong", SYMBOL_PONG, },
  { "zonk", SYMBOL_ZONK, },
  { NULL, 0, },
}, *symbol_p = symbols;

static gfloat ping = 0;
static gfloat pong = 0;
static gfloat zonk = 0;

static guint
parse_symbol (GScanner *scanner)
{
  guint symbol;
  gboolean negate = FALSE;

  /* expect a valid symbol */
  g_scanner_get_next_token (scanner);
  symbol = scanner->token;
  if (symbol &lt; SYMBOL_PING ||
      symbol > SYMBOL_ZONK)
    return G_TOKEN_SYMBOL;

  /* expect '=' */
  g_scanner_get_next_token (scanner);
  if (scanner->token != '=')
    return '=';

  /* feature optional '-' */
  g_scanner_peek_next_token (scanner);
  if (scanner->next_token == '-')
    {
      g_scanner_get_next_token (scanner);
      negate = !negate;
    }

  /* expect a float (ints are converted to floats on the fly) */
  g_scanner_get_next_token (scanner);
  if (scanner->token != G_TOKEN_FLOAT)
    return G_TOKEN_FLOAT;

  /* make sure the next token is a ';' */
  if (g_scanner_peek_next_token (scanner) != ';')
    {
      /* not so, eat up the non-semicolon and error out */
      g_scanner_get_next_token (scanner);
      return ';';
    }

  /* assign value, eat the semicolon and exit successfully */
  switch (symbol)
    {
    case SYMBOL_PING:
      ping = negate ? - scanner->value.v_float : scanner->value.v_float;
      break;
    case SYMBOL_PONG:
      pong = negate ? - scanner->value.v_float : scanner->value.v_float;
      break;
    case SYMBOL_ZONK:
      zonk = negate ? - scanner->value.v_float : scanner->value.v_float;
      break;
    }
  g_scanner_get_next_token (scanner);

  return G_TOKEN_NONE;
}

int
main (int argc, char *argv[])
{
  GScanner *scanner;
  guint expected_token;

  scanner = g_scanner_new (NULL);

  /* adjust lexing behaviour to suit our needs
   */
  /* convert non-floats (octal values, hex values...) to G_TOKEN_INT */
  scanner->config->numbers_2_int = TRUE;
  /* convert G_TOKEN_INT to G_TOKEN_FLOAT */
  scanner->config->int_2_float = TRUE;
  /* don't return G_TOKEN_SYMBOL, but the symbol's value */
  scanner->config->symbol_2_token = TRUE;

  /* load symbols into the scanner */
  while (symbol_p->symbol_name)
    {
      g_scanner_add_symbol (scanner,
                            symbol_p->symbol_name,
                            GINT_TO_POINTER (symbol_p->symbol_token));
      symbol_p++;
    }

  /* feed in the text */
  g_scanner_input_text (scanner, test_text, strlen (test_text));

  /* give the error handler an idea on how the input is named */
  scanner->input_name = "test text";

  /* scanning loop, we parse the input until its end is reached,
   * the scanner encountered a lexing error, or our sub routine came
   * across invalid syntax
   */
  do
    {
      expected_token = parse_symbol (scanner);
      
      g_scanner_peek_next_token (scanner);
    }
  while (expected_token == G_TOKEN_NONE &amp;&amp;
         scanner->next_token != G_TOKEN_EOF &amp;&amp;
         scanner->next_token != G_TOKEN_ERROR);

  /* give an error message upon syntax errors */
  if (expected_token != G_TOKEN_NONE)
    g_scanner_unexp_token (scanner, expected_token, NULL, "symbol", NULL, NULL, TRUE);

  /* finsish parsing */
  g_scanner_destroy (scanner);

  /* print results */
  g_print ("ping: %f\n", ping);
  g_print ("pong: %f\n", pong);
  g_print ("zonk: %f\n", zonk);
  
  return 0;
}
</PRE>
</P>
<P>You need to understand that the scanner will parse its input and
tokenize it, it is up to you to interpret these tokens, not define
their types before they get parsed, e.g. watch gscanner parse a
string:</P>
<P>
<PRE>
"hi i am 17"
 |  | |  |
 |  | |  v
 |  | v  TOKEN_INT, value: 17
 |  v TOKEN_IDENTIFIER, value: "am"
 v  TOKEN_CHAR, value: 'i'
TOKEN_IDENTIFIER, value: "hi"
</PRE>
</P>
<P>If you configure the scanner with:
<PRE>
scanner->config->int_2_float = TRUE;
scanner->config->char_2_token = TRUE;
scanner->config->scan_symbols = TRUE;
</PRE>
</P>
<P>and add "am" as a symbol with
<PRE>
g_scanner_add_symbol (scanner, "am", "symbol value");
</PRE>
</P>
<P>GScanner will parse it as</P>
<P>
<PRE>
"hi i am 17"
 |  | |  |
 |  | |  v
 |  | v  TOKEN_FLOAT, value: 17.0  (automatic int->float conversion)
 |  | TOKEN_SYMBOL, value: "symbol value"  (a successfull hash table lookup
 |  |                                       turned a TOKEN_IDENTIFIER into a
 |  |                                       TOKEN_SYMBOL and took over the
 |  v                                       symbol's value)
 v  'i'  ('i' can be a valid token as well, as all chars >0 and &lt;256)
TOKEN_IDENTIFIER, value: "hi"
</PRE>
</P>
<P>You need to match the token sequence with your code, and if you encounter
something that you don't want, you error out:</P>
<P>
<PRE>
/* expect an identifier ("hi") */
g_scanner_get_next_token (scanner);
if (scanner->token != G_TOKEN_IDENTIFIER)
  return G_TOKEN_IDENTIFIER;
/* expect a token 'i' */
g_scanner_get_next_token (scanner);
if (scanner->token != 'i')
  return 'i';
/* expect a symbol ("am") */
g_scanner_get_next_token (scanner);
if (scanner->token != G_TOKEN_SYMBOL)
  return G_TOKEN_SYMBOL;
/* expect a float (17.0) */
g_scanner_get_next_token (scanner);
if (scanner->token != G_TOKEN_FLOAT)
  return G_TOKEN_FLOAT;
</PRE>
</P>
<P>If you got past here, you have parsed "hi i am 17" and would have
accepted "dooh i am 42" and  "bah i am 0.75" as well, but you would
have not accepted "hi 7 am 17" or "hi i hi 17".</P>

<HR NOSHADE>
<A HREF="gtkfaq-9.html">Next</A>
<A HREF="gtkfaq-7.html">Previous</A>
<A HREF="gtkfaq.html#toc8">Contents</A>
</BODY>
</HTML>