How to create a generic C free function .
- by nomemory
I have some C structures related to a 'list' data structure.
They look like this.
struct nmlist_element_s {
void *data;
struct nmlist_element_s *next;
};
typedef struct nmlist_element_s nmlist_element;
struct nmlist_s {
void (*destructor)(void *data);
int (*cmp)(const void *e1, const void *e2);
unsigned int size;
nmlist_element *head;
nmlist_element *tail;
};
typedef struct nmlist_s nmlist;
This way I can have different data types being hold in "nmlist_element-data" .
The "constructor" (in terms of OOP) has the following signature:
nmlist *nmlist_alloc(void (*destructor)(void *data));
Where "destructor" is specific function that de-allocated "data" (being hold by the nmlist_element).
If I want to have a list containing integers as data, my "destructor" would like this:
void int_destructor(void *data)
{
free((int*)data);
}
Still i find it rather "unfriendly" for me to write a destructor functions for every simple primitive data type. So is there a trick to write something like this ? (for primitives):
void "x"_destructor(void *data, "x")
{
free(("x" *)data);
}
PS: I am not a macro fan myself, and in my short experience regarding C, i don't use them, unless necessary.