I’m working on a library which can be used to achieve most OOP functionality of OO languages in C, by providing an API (not by extending the syntax).
I’ve written 2 articles (artc. 1, artc. 2) so far about getting OO like behaviour in C, and will write a few more about the more advanced stuff which I’m still experimenting with.
You can download the source of the API I have developed so far here, which by the way is far from finished. Stuff will change, and I am aware of some issues.
I’ll explain how it works in the next parts in the ‘Objects in C’ serie, but to give you a kickstart in the code I’ll explain it briefly:
Every object has got a pointer to its type and its toplevel object, which usualy is itself. The type instance pointed to from the instance provides the size, constructor, destructor and the interfacegetter.
The GetInterface
function in the type (the interfacegetter) returns a pointer to an instance of an object of the given type if supported by the object.
Using interfaces can serve different purposes:
Exposing certain objectwide functionality
((ICloneable*)object->top->type->GetInterface(object->top->type, object->top, GetICloneableType()))->Clone(object->top);
This code will return a Clone of the object
, even if only the object is passed by a not top level pointer. Using the top
pointer ensures proper polyforism, and enables the ability for the top most class to hide, or show some internal functionality of wrapped objects.
Exposing interface specific functionality
((String*)object->type->GetInterface(object->type, object, GetIToStringAble()))->ToString(object);
It now depends on which interface of a certain object is passed which behaviour results.
And more.. and more.. which I will explain in the coming articles.
One thought on “Intrepid C – ‘Objects’ in C”