class.h
2.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#ifndef __CLASS_H__
#define __CLASS_H__
#include <stdarg.h>
#include <sys/types.h>
#include <string.h>
#include <assert.h>
#include "interface.h"
#define _ISOC99_SOURCE
#define CLASS_MAGIC 0xFEFE
#define CLASS(name) \
struct c_##name; \
typedef struct c_##name * name; \
extern struct class * const _##name; \
struct c_##name
#define EXTENDS(parent) \
const char _[sizeof(struct c_##parent)]
#define _NULL NULL
#define CREATE_CLASS(name,_parent,...) \
static struct class c_##name; \
static void _classInit_(void) { \
c_##name.parent = _##_parent; \
c_##name.init = NULL; \
} \
static struct class c_##name = { \
CLASS_MAGIC, \
NULL, \
sizeof(struct c_##name), \
_classInit_, \
INIT_IMPL(__VA_ARGS__) \
}; struct class * const _##name = &c_##name
/**
* @TODO: actually i use gcc feature ## for variadoc... think about
* a way to make this standard.
*/
#define CALL(object,_iface,method,...) \
do { \
class_ptr class = class_getClass((object)); \
struct i_##_iface * iface; \
if (class->init) class->init(); \
iface = (struct i_##_iface *)class_getInterface(&class, &i_##_iface); \
while ((NULL == iface || NULL == iface->method) && HAS_PARENT(class)) { \
class = class->parent; \
if (class->init) class->init(); \
iface = (struct i_##_iface *)class_getInterface(&class, &i_##_iface); \
}; \
assert(NULL != iface->method); \
iface->method(object, ##__VA_ARGS__); \
} while(0)
#define IFACE_GET(class,iface) (interfaceGet(&((class)->impl),(iface)))
#define IFACE_EXISTS(class,iface) (NULL != IFACE_GET((class),(iface)))
#define HAS_PARENT(class) (NULL != ((class)->parent))
typedef void (* fptr_classInit)(void);
struct class;
typedef struct class * class_ptr;
struct class {
const int magic;
class_ptr parent;
size_t object_size;
fptr_classInit init;
struct iface_impl impl;
};
extern inline void * class_getInterface(class_ptr *, iface_ptr);
extern inline class_ptr class_getClass(void *);
#endif // __CLASS_H__
// vim: set ts=4 sw=4: