beordle / obj.h

A single-header supports OOP in pure C.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

obj.h

A single-header supports OOP in pure C
- just a hacking on assembly -

Foo f = new(Foo)(10);
assert(f->get() == 10);
f->base.release();

Features

  • 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.

Usage

  • Just add obj.h to your C source.
  • See tests for more.

Platform support

GCC 4+ MSVC 14+ Clang 5+ TCC 0.9
Windows (x86 / x64)
Linux (i386 / x86_x64) _
Mac OSX (i386 / x86_64) _ _

How it works?

$object {
    public:  (...) +---------------> [USER/EXTERNAL]
    private: (...)                         ^
    memory:    [pool]                      |
} *self;      -- + --         +------------+
                 |            |
dynamic  _       |    <--+ method: closure [self] (args, ...)
allocate +--->   |                    |       \-----> { function }
                 v                    v
constructor -> object  | +-----> [INTERNAL]
destructor() ->  X

Closure function?

  • 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 and x86_64 only.
.data = $self
> x86
  | jmp $addr
> x86_64  
  | push rax
  | mov  rax, $addr
  | jmp  rax

Ref: https://stackoverflow.com/a/9819716

C++ comparison

// 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();

ko-fi

About

A single-header supports OOP in pure C.

License:MIT License


Languages

Language:C 91.8%Language:C++ 6.7%Language:Lua 1.5%