GRASS GIS 8 Programmer's Manual  8.5.0dev(2024)-d6dec75dd4
gis/handler.c
Go to the documentation of this file.
1 /*!
2  \file lib/gis/handler.c
3 
4  \brief GIS Library - Error handlers
5 
6  (C) 2010-2011 by the GRASS Development Team
7 
8  This program is free software under the GNU General Public
9  License (>=v2). Read the file COPYING that comes with GRASS
10  for details.
11 
12  \author Glynn Clements
13  */
14 
15 #include <stddef.h>
16 #include <grass/gis.h>
17 
18 /*!
19  \brief Error handler (see G_add_error_handler() for usage)
20  */
21 struct handler {
22  /*!
23  \brief Pointer to the handler routine
24  */
25  void (*func)(void *);
26  /*!
27  \brief Pointer to closure data
28  */
29  void *closure;
30 };
31 
32 static struct handler *handlers;
33 
34 static int num_handlers;
35 static int max_handlers;
36 
37 static struct handler *alloc_handler(void)
38 {
39  int i;
40 
41  for (i = 0; i < num_handlers; i++) {
42  struct handler *h = &handlers[i];
43 
44  if (!h->func)
45  return h;
46  }
47 
48  if (num_handlers >= max_handlers) {
49  max_handlers += 10;
50  handlers = G_realloc(handlers, max_handlers * sizeof(struct handler));
51  }
52 
53  return &handlers[num_handlers++];
54 }
55 
56 /*!
57  \brief Add new error handler
58 
59  Example
60  \code
61  static void error_handler(void *p) {
62  const char *map = (const char *) p;
63  Vect_delete(map);
64  }
65  G_add_error_handler(error_handler, new->answer);
66  \endcode
67 
68  \param func handler to add
69  \param closure pointer to closure data
70  */
71 void G_add_error_handler(void (*func)(void *), void *closure)
72 {
73  struct handler *h = alloc_handler();
74 
75  h->func = func;
76  h->closure = closure;
77 }
78 
79 /*!
80  \brief Remove existing error handler
81 
82  \param func handler to be remove
83  \param closure pointer to closure data
84  */
85 void G_remove_error_handler(void (*func)(void *), void *closure)
86 {
87  int i;
88 
89  for (i = 0; i < num_handlers; i++) {
90  struct handler *h = &handlers[i];
91 
92  if (h->func == func && h->closure == closure) {
93  h->func = NULL;
94  h->closure = NULL;
95  }
96  }
97 }
98 
99 /*!
100  \brief Call available error handlers (internal use only)
101  */
103 {
104  int i;
105 
106  for (i = 0; i < num_handlers; i++) {
107  struct handler *h = &handlers[i];
108 
109  if (h->func)
110  (*h->func)(h->closure);
111  }
112 }
#define NULL
Definition: ccmath.h:32
#define G_realloc(p, n)
Definition: defs/gis.h:96
void G_add_error_handler(void(*func)(void *), void *closure)
Add new error handler.
Definition: gis/handler.c:71
void G__call_error_handlers(void)
Call available error handlers (internal use only)
Definition: gis/handler.c:102
void G_remove_error_handler(void(*func)(void *), void *closure)
Remove existing error handler.
Definition: gis/handler.c:85