Skip to content

Instantly share code, notes, and snippets.

@caotic123
Last active March 17, 2024 07:29
Show Gist options
  • Save caotic123/318719d876f844037c4f6a96af7186a4 to your computer and use it in GitHub Desktop.
Save caotic123/318719d876f844037c4f6a96af7186a4 to your computer and use it in GitHub Desktop.
Basic vtables for emulate OOP
#include <stdio.h>
#define Method(x, y, type) ((type)(x->methods[y] ))(x)
#pragma pack(1)
typedef struct {
void* space;
void** methods;
size_t size;
int methods_size;
} table;
table* Animal(char* a, char* (*eat) (struct table* self)) {
table* animal = malloc(sizeof(table));
animal->space = malloc(256);
animal->size = 256;
memcpy(animal->space, a, strlen(a)+1);
animal->methods = malloc(sizeof(void*));
animal->methods[0] = eat;
animal->methods_size = 1;
return animal;
}
table* Wolf(table* animal, char* a, char* (sound) (struct table* self)) {
memcpy(animal->space, a, strlen(a)+1);
animal->methods_size++;
animal->methods = realloc(animal->methods, animal->methods_size*sizeof(void*));
animal->methods[1] = sound;
return animal;
}
table* Dog(table* wolf, char* a, char* (sound) (struct table* self)) {
memcpy(wolf->space, a, strlen(a)+1);
wolf->methods_size++;
wolf->methods = realloc(wolf->methods, wolf->methods_size*sizeof(void*));
wolf->methods[2] = sound;
return wolf;
}
int main()
{
void eat(table* self) {
printf("I am a %s\n", (char*)self->space);
}
table* animal = Animal("Animal", eat);
Method(animal, 0, void (*) (table* self));
void howl(table* self) {
printf("howww\n");
}
table* wolf = Wolf(animal, "Wolf", howl);
Method(wolf, 0, void (*) (table* self));
Method(wolf, 1, void (*) (table* self));
void bark(table* self) {
printf("au au");
}
table* dog = Dog(wolf, "Dog", bark);
Method(dog, 0, void (*) (table* self));
Method(dog, 1, void (*) (table* self)); // A dog can also howl
Method(dog, 2, void (*) (table* self));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment