Foo f = new(Foo)(10);
assert(f->get() == 10);
f->base.release();
- Support OOP in pure C (inspired by C++ and Java).
- Support classes, objects.
- Support public, private members.
- Support constructor, destructor.
- Support data abstraction.
- Support inheritance.
- No dependencies.
- Just add
obj.h
to your C source. - See tests for more.
GCC 4+ | MSVC 14+ | Clang 5+ | TCC 0.9 | |
---|---|---|---|---|
Windows (x86 / x64) | ✅ | ✅ | ✅ | ✅ |
Linux (i386 / x86_x64) | ✅ | _ | ✅ | ✅ |
Mac OSX (i386 / x86_64) | ✅ | _ | ✅ | _ |
$object {
public: (...) +---------------> [USER/EXTERNAL]
private: (...) ^
memory: [pool] |
} *self; -- + -- +------------+
| |
dynamic _ | <--+ method: closure [self] (args, ...)
allocate +---> | | \-----> { function }
v v
constructor -> object | +-----> [INTERNAL]
destructor() -> X
- This is a fork of clofn.
- Just copy function header and inject some code to pre-allocate self inside method.
- Using power of C macro and struct to provide
obj.h
. - Currently, support
x86
andx86_64
only.
.data = $self
> x86
| jmp $addr
> x86_64
| push rax
| mov rax, $addr
| jmp rax
Ref: https://stackoverflow.com/a/9819716
// C++ native OOP // C with obj.h
class Foo { | class(Foo, public(
public: | int (*get)();
Foo(int bar); | ), private(
int get(); | int bar;
private: | ));
int bar; |
} | ctor(Foo)(int bar) {
| obj_setup(Foo);
Foo::Foo(int bar) { | obj_bind(Foo, get);
this->bar = bar; | self->bar = bar;
} | obj_done(Foo);
| }
int Foo::get() { |
return this->bar; | method(Foo, int, get)() {
} | obj_prepare(Foo);
| return self->bar;
Foo *f = new Foo(15); | }
f->get(); |
delete f; | Foo f = new(Foo)(15);
| f->get();
| f->base.release();