objects

objects in c
git clone https://noulin.net/git/objects.git
Log | Files | Refs | README | LICENSE

commit bebbad2b753d78de1ab7c075ba1bd67090fced7f
parent ba57aa378275c57e32349ccba6d9a5df411f21df
Author: Remy Noulin (Spartatek) <remy.noulin@spartatek.se>
Date:   Sun, 26 Feb 2017 10:00:45 +0100

add free to free internal object buffers

main.c | 32 +++++++++++++++++++++++++++++---
1 file changed, 29 insertions(+), 3 deletions(-)

Diffstat:
Mmain.c | 32+++++++++++++++++++++++++++++---
1 file changed, 29 insertions(+), 3 deletions(-)

diff --git a/main.c b/main.c @@ -3,28 +3,35 @@ #include <string.h> // Generics +#define freeO(obj) obj.free(&obj) +#define freeOPointer(obj) obj->free(&obj) #define deleteO(obj) obj->terminate(&obj) - // Class: class typedef struct class classt; typedef void (*printt)(classt *self, char *string); +typedef void (*freeClasstt)(classt *self); typedef void (*terminateClasstt)(classt **self); +typedef classt* (*duplicateClasstt)(classt **self); struct class { int a; char *s; printt print; terminateClasstt terminate; + duplicateClasstt duplicate; + freeClasstt free; }; // Initiate/Terminate Objects #define createclasst(obj) classt obj; initiateclasst(&obj) #define createAllocateclasst(obj) classt *obj; initiateAllocateclasst(&obj) void initiateclasst(classt *self); +void freeclasst(classt *self); void terminateclasst(classt **self); +classt* duplicateclasst(classt **self); // Prototypes void print(classt *self, char *s); @@ -37,17 +44,34 @@ void initiateAllocateclasst(classt **self) { void initiateclasst(classt *self) { + self->free = freeclasst; self->terminate = terminateclasst; + self->duplicate = duplicateclasst; self->a = 0; self->s = NULL; self->print = print; } +void freeclasst(classt *self) { + if (self->s) + free(self->s); +} + void terminateclasst(classt **self) { - if ((*self)->s) - free((*self)->s); + (*self)->free(*self); free((*self)); + *self = NULL; +} + +classt* duplicateclasst(classt **self) { + + createAllocateclasst(r); + + r->a = (*self)->a; + if ((*self)->s) + r->s = strdup((*self)->s); + return r; } // Members @@ -61,6 +85,7 @@ void main() { createclasst(obj1); obj1.print(&obj1, "\nRegular Object\n"); printf("\ndirect access %s", obj1.s); + obj1.free(&obj1); createAllocateclasst(obj2); obj2->print(obj2, "\nObject in heap\n"); @@ -70,6 +95,7 @@ void main() { classt obj3; initiateclasst(&obj3); obj3.print(&obj3, "\n\nObj 3\n"); + freeO(obj3); classt *obj4; initiateAllocateclasst(&obj4);