Created
May 21, 2021 04:30
-
-
Save abcarroll/b7628f635ee032496b67bb619c267ce7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
//#include "test.h" | |
/** | |
* The following two struct's are basically an interface. | |
*/ | |
// The VTable which will only ever be a single copy (normally) | |
struct _SomeClass_VTable | |
{ | |
// Constructor | |
struct _SomeClass_Instance*(*ctr)(void); | |
// Method one will add the int to the instance value | |
void(*MethodOne)(struct _SomeClass_Instance*, int); | |
// Method two will call methodOne twice. | |
void(*MethodTwo)(struct _SomeClass_Instance*, int); | |
} _SomeClass_VTable; | |
// The instance class, there will be one of these per instance. | |
struct _SomeClass_Instance | |
{ | |
struct _SomeClass_VTable* vt; | |
// properties | |
int val; | |
}; | |
/** | |
* Next three definitions are like a "class SomeClass implements <the two structs>" | |
*/ | |
// Constructor | |
struct _SomeClass_Instance* _SomeClass_Ctr(void) | |
{ | |
struct _SomeClass_Instance* i = malloc(sizeof(struct _SomeClass_Instance)); | |
i->vt = &_SomeClass_VTable; | |
i->val = 0; | |
return i; | |
} | |
void _SomeClass_MethodOne(struct _SomeClass_Instance* _this, int x) | |
{ | |
_this->val += x; | |
} | |
void _SomeClass_MethodTwo(struct _SomeClass_Instance*_this, int x) | |
{ | |
// call "this->MethodOne(x)" twice. | |
_this->vt->MethodOne(_this, x); | |
_this->vt->MethodOne(_this, x); | |
} | |
/** | |
* main | |
*/ | |
int main(int argc, char* argv[]) | |
{ | |
// setup | |
_SomeClass_VTable.ctr = _SomeClass_Ctr; | |
_SomeClass_VTable.MethodOne = _SomeClass_MethodOne; | |
_SomeClass_VTable.MethodTwo = _SomeClass_MethodTwo; | |
// new SomeClass(); | |
struct _SomeClass_Instance *instanceOne = _SomeClass_VTable.ctr(); | |
instanceOne->vt->MethodOne(instanceOne, 5); | |
instanceOne->vt->MethodTwo(instanceOne, 1); | |
printf("Value of member: %i", instanceOne->val); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment