#include #include "cog.h" struct cog { float radius; float circumference; int numteeth; }; static int isvalidcog(cog_t *); /* * In the ctor (constructor) you can do ALL KINDS OF THINGS to "mark" your * cogs so that when someone passes a pointer into an interface function you * can perform thorough validation of that cog pointer and what it points to. * This keeps bad things from happening if people accidentally pass bogus cog * pointers in across your interface. We don't do any of that in this example. */ extern cog_t * cog_ctor(void) { cog_t * rslt; rslt = calloc(1, sizeof(struct cog)); return rslt; } /* * For the dtor (destructor) we require the user to pass a pointer to a pointer * to a cog... this requires that the user be able to take the address of the * cog ptr that is passed in to the dtor, which decreases the likelihood that * someone will pass in a wild pointer, but it can still happen. This also * allows us to set the original pointer to NULL after the memory is released * so that if the user checks he can tell that the cog is no longer valid. */ extern void cog_dtor(cog_t ** p) { if (p == NULL || *p == NULL) /* * User made a mistake... */ return; free(*p); *p = NULL; } extern float cog_radius(cog_t * cog) { if (!isvalidcog(cog)) return Cog_InvalidRadius; else return (*cog).radius; } extern int cog_radius_set(cog_t * cog, float radius) { if (!isvalidcog(cog)) return 0; cog->radius = radius; return 1; } static int isvalidcog(cog_t * cog) { if (cog == NULL) return 0; return 1; }