objects

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

commit c3826b7b2e40fb610391d73daa9293ac1f31953b
parent 7c08857e530d2db7b43aa7c0eba5c336cd34dc91
Author: Remy Noulin (Spartatek) <remy.noulin@spartatek.se>
Date:   Tue, 21 Feb 2017 17:15:09 +0100

add createO createAllocateO and delete

main.c | 46 +++++++++++++++++++++++++++++++++++++---------
1 file changed, 37 insertions(+), 9 deletions(-)

Diffstat:
Mmain.c | 46+++++++++++++++++++++++++++++++++++++---------
1 file changed, 37 insertions(+), 9 deletions(-)

diff --git a/main.c b/main.c @@ -1,27 +1,38 @@ #include <stdlib.h> #include <stdio.h> +#include <string.h> + +// Generics +#define createO(type, obj) type obj; initiateclasst(&obj) +#define createAllocateO(type, obj) type *obj; initiateAllocateclasst(&obj) + +#define deleteO(obj) obj->terminate(&obj) + -void print(char *s) { - printf(s); -} // Class: class typedef struct class classt; -// Members -typedef void (*printt)(char *string); + +typedef void (*printt)(classt *self, char *string); typedef void (*terminateClasstt)(classt **self); struct class { int a; + char *s; printt print; terminateClasstt terminate; }; + // Initiate/Terminate Objects #define createclasst(obj) classt obj; initiateclasst(&obj) #define createAllocateclasst(obj) classt *obj; initiateAllocateclasst(&obj) +// (use generics instead of these macros ^: createO and createAllocateO) void initiateclasst(classt *self); void terminateclasst(classt **self); +// Prototypes +void print(classt *self, char *s); + void initiateAllocateclasst(classt **self) { (*self) = malloc(sizeof(classt)); @@ -32,6 +43,7 @@ void initiateclasst(classt *self) { self->terminate = terminateclasst; self->a = 0; + self->s = NULL; self->print = print; } @@ -40,22 +52,38 @@ void terminateclasst(classt **self) { free((*self)); } +// Members +void print(classt *self, char *s) { + self->s = strdup(s); + printf(self->s); +} + void main() { createclasst(obj1); - obj1.print("\nRegular Object\n"); + obj1.print(&obj1, "\nRegular Object\n"); + printf("\ndirect access %s", obj1.s); createAllocateclasst(obj2); - obj2->print("\nObject in heap\n"); + obj2->print(obj2, "\nObject in heap\n"); obj2->terminate(&obj2); // initiate alternative classt obj3; initiateclasst(&obj3); - obj3.print("\n\nobj 3\n"); + obj3.print(&obj3, "\n\nObj 3\n"); classt *obj4; initiateAllocateclasst(&obj4); - obj4->print("\nOBJ 4\n"); + obj4->print(obj4, "\nOBJ 4\n"); obj4->terminate(&obj4); + + // + + createO(classt, obj5); + obj5.print(&obj5, "\nRegular Object 5\n"); + + createAllocateO(classt, obj6); + obj6->print(obj6, "\nObject 6 in heap\n"); + deleteO(obj6); }