Whenever using Eina we must include it:
For this example we are going to define two classes, person and pilot, and since every pilot is a person we use inheritance. To be type safe we are going to add EINA_MAGIC to our classes:
- Note
- The values of BASETYPE_MAGIC and SUBTYPE_MAGIC have no meaning, the only important thing about them is that they be unique.
Here we have a function to create a perso given a name, nothing too fancy:
And now the counterpart, a function the free a person.
Before we start releasing resources we check that the pointer we were given actually points to a person, and if not we will print an error message and quit:
- Note
- EINA_MAGIC_FAIL is a macro that make's it easy to print an appropriate (and consistent) error message. Now knowing that ptr is indeed of type person we prooced to set EINA_MAGIC to EINA_MAGIC_NONE and free alocated memory: EINA_MAGIC_SET(ptr, EINA_MAGIC_NONE);free(ptr->name);free(ptr);}#define EINA_MAGIC_NONERandom value for specifying that a structure using the magic feature has already been freed.Definition eina_magic.h:202
- Setting EINA_MAGIC to EINA_MAGIC_NONE is important to prevent the struct from being used after freed.
Now we have our function to create a pilot, this one is a little more complex because we need to set EINA_MAGIC for the pilot and pilot->base, this is very important so that checking the EINA_MAGIC of (person*)my_pilot will work:
The function to free a pilot is not too different from the one that frees a person:
We also create functions to print a person or a pilot that check the type of the pointers they receive:
And on to our main function where we declare some variables and initialize Eina:
For Eina to be able to provide more informative error messages we are going to give names to our EINA_MAGIC types:
Since our types won't live longer than the scope of the current function we can set the name without eina making a copy of the string:
Now we create a person, a pilot and print both as persons:
Now we try to print both as pilots, which will obvisouly not work since base is not a pilot:
That's all folks:
See full source here.