Full-featured interfaces for C99
(Based on examples/shape.c.)
Output
perim = 24
perim = 120
perim = 60
perim = 300Minimum boilerplate. Forget about maintaining virtual tables -- just write impl(Shape, Rectangle) and Interface99 will do it for you!
Portable. Everything you need is a standard-conforming C99 compiler; neither the standard library, nor compiler/platform-specific functionality or VLA are required.
Predictable. Interface99 comes with formal code generation semantics, meaning that the generated data layout is guaranteed to always be the same.
Comprehensible errors. Interface99 is resilient to bad code.
Battle-tested. Interface99 is used at OpenIPC to develop real-time streaming software for IP cameras; this includes an RTSP 1.0 implementation along with ~50k lines of private code.
| Feature | Status | Description |
|---|---|---|
| Multiple interface inheritance | ✅ | A type can inherit multiple interfaces at the same time. |
| Superinterfaces | ✅ | One interface can require a set of other interfaces to be implemented as well. |
| Marker interfaces | ✅ | An interface with no functions. |
| Single/Dynamic dispatch | ✅ | Determine a function to be called at runtime based on self. |
| Multiple dispatch | ❌ | Determine a function to be called at runtime based on multiple arguments. Likely to never going to be implemented. |
| Dynamic objects of multiple interfaces | ✅ | Given interfaces Foo and Bar, you can construct an object of both interfaces, FooBar obj. |
| Default implementations | ✅ | Some interface functions may be given default implementations. A default function can call other functions and vice versa. |
| Data and implementation separation | ✅ | New interfaces can be implemented for existing types. |
Interface99 consists of one header file interface99.h and one dependency Metalang99. To use it in your project, you need to:
interface99 and metalang99/include to your include directories.-ftrack-macro-expansion=0 (GCC) or -fmacro-backtrace-limit=1 (Clang) to avoid useless macro expansion errors.If you use CMake, the recommended way is FetchContent:
include(FetchContent)
FetchContent_Declare(
interface99
URL https://github.com/hirrolot/interface99/archive/refs/tags/vx.y.z.tar.gz # vx.y.z
)
FetchContent_MakeAvailable(interface99)
target_link_libraries(MyProject interface99)
# Disable full macro expansion backtraces for Metalang99.
if(CMAKE_C_COMPILER_ID STREQUAL "Clang")
target_compile_options(MyProject PRIVATE -fmacro-backtrace-limit=1)
elseif(CMAKE_C_COMPILER_ID STREQUAL "GNU")
target_compile_options(MyProject PRIVATE -ftrack-macro-expansion=0)
endif()(By default, interface99/CMakeLists.txt downloads Metalang99 v1.13.5 from the GitHub releases; if you want to override this behaviour, you can do so by invoking FetchContent_Declare earlier.)
Optionally, you can precompile headers in your project that rely on Interface99. This will decrease compilation time, because the headers will not be compiled each time they are included.
Happy hacking!
This section is based on a collection of well-documented examples, each of which demonstrates one specific aspect of Interface99.
Syntax: interface(Shape);
An interface definition expands to a virtual table structure and a so-called interface object type. In the case of examples/shape.c:
// interface(Shape);
typedef struct ShapeVTable ShapeVTable;
typedef struct Shape Shape;
struct ShapeVTable {
int (*perim)(const VSelf);
void (*scale)(VSelf, int factor);
};
struct Shape {
void *self;
const ShapeVTable *vptr;
};Here, Shape.self is the pointer to an object whose type implements Shape, and Shape.vptr points to a corresponding virtual table instance. Inside ShapeVTable, you can observe the mysterious VSelf bits -- they expand to parameters of type void * restrict (with extra const for perim); when calling these methods, Interface99 will substitute Shape.self for these parameters.
Usually, interface definitions go in *.h files.
| Linkage | Syntax |
|---|---|
| Internal | impl(Shape, Rectangle); |
| External | implExtern(Shape, Rectangle); |
An implementation definition expands to nothing but a virtual table instance of a particular implementer. In the case of examples/shape.c:
// impl(Shape, Rectangle);
static const ShapeVTable Rectangle_Shape_impl = {
.perim = Rectangle_perim,
.scale = Rectangle_scale,
};(If you were using implExtern, this definition would be extern likewise.)
Note that inside function implementations, we use VSELF, which simply casts the parameter introduced by VSelf to a user-defined type (const Rectangle or Rectangle in our case):
int Rectangle_perim(const VSelf) {
VSELF(const Rectangle);
return (self->a + self->b) * 2;
}
void Rectangle_scale(VSelf, int factor) {
VSELF(Rectangle);
self->a *= factor;
self->b *= factor;
}Once an interface and its implementations are both generated, it is time to instantiate an interface object and invoke some functions upon it.
First of all, to instantiate Shape, use the DYN_LIT macro:
Shape r = DYN_LIT(Rectangle, Shape, {5, 7});
test(r);Here, DYN_LIT(Rectangle, Shape, {5, 7}) creates Shape by assigning Shape.self to &(Rectangle){5, 7} and Shape.vptr to the aforementioned &Rectangle_Shape_impl. Eventually, you can accept Shape as a function parameter and perform dynamic dispatch through the VCALL macro:
void test(Shape shape) {
printf("perim = %d\n", VCALL(shape, perim));
VCALL(shape, scale, 5);
printf("perim = %d\n", VCALL(shape, perim));
}Finally, just a few brief notes:
VCALL, you also have VCALL_OBJ, VCALL_SUPER, and VCALL_SUPER_OBJ. They all serve a different purpose; for more information, please refer to their documentation.DYN is used more often than DYN_LIT; it just accepts an ordinary pointer instead of an initialiser list, which means that you can malloc it beforehand.self, you can invoke it as obj.vptr->foo(...).VTABLE(T, Iface).foo(...).Congratulations, this is all you need to know to write most of the stuff!
Interface99 has the feature called superinterfaces, or interface requirements. examples/airplane.c demonstrates how to extend interfaces with new functionality:
#define Vehicle_IFACE \
vfunc(void, move_forward, VSelf, int distance) \
vfunc(void, move_back, VSelf, int distance)
interface(Vehicle);
#define Airplane_IFACE \
vfunc(void, move_up, VSelf, int distance) \
vfunc(void, move_down, VSelf, int distance)
#define Airplane_EXTENDS (Vehicle)
interface(Airplane);(Note that #define Airplane_EXTENDS must appear prior to interface(Airplane);.)
Here, Airplane extends Vehicle with the new functions move_up and move_down. Everywhere you have Airplane, you can also operate Vehicle:
Airplane my_airplane = DYN_LIT(MyAirplane, Airplane, {.x = 0, .y = 0});
VCALL_SUPER(my_airplane, Vehicle, move_forward, 10);
VCALL_SUPER(my_airplane, Vehicle, move_back, 3);Internally, Interface99 embeds superinterfaces' virtual tables into those of subinterfaces, thereby forming a virtual table hierarchy. For example, you can specify Repairable and Armoured along with Vehicle, and they all will be included into AirplaneVTable like so:
// #define Airplane_EXTENDS (Vehicle, Repairable, Armoured)
typedef struct AirplaneVTable {
void (*move_up)(VSelf, int distance);
void (*move_down)(VSelf, int distance);
const VehicleVTable *Vehicle;
const RepairableVTable *Repairable;
const ArmouredVTable *Armoured;
} AirplaneVTable;Sometimes we wish to define default behaviour for several implementers; this is supported by default implementations.
Take a look at examples/default_impl.c. In this example, we define the interface Droid:
#define Droid_IFACE \
vfunc(const char *, name, void) \
vfuncDefault(void, turn_on, Droid droid)
interface(Droid);The macro vfuncDefault tells Interface99 to use the default implementation for turn_on automatically. But where is it located? Here:
void Droid_turn_on(Droid droid) {
printf("Turning on %s...\n", droid.vptr->name());
}As you can see, default implementations follow a strict naming convention, _ , which provides Interface99 with sufficient information to generate a virtual table. Additionally, as a developer, you can also rely on this convention and call a default function of a third-party interface. For C_3PO, we use the default implementation of turn_on, and the resulting virtual table would look like this:
static const DroidVTable C_3PO_Droid_impl = {
.name = C_3PO_name,
.turn_on = Droid_turn_on,
};But for R2_D2, we use a custom implementation R2_D2_turn_on:
void R2_D2_turn_on(Droid droid) {
Droid_turn_on(droid);
puts("Waaaaoow!");
}
#define R2_D2_turn_on_CUSTOM ()
impl(Droid, R2_D2);(R2_D2_turn_on_CUSTOM tells Interface99 to use the custom implementation instead of the default one; this is because it is impossible to detect at compile-time whether a specific function is defined or not.)
And the virtual table would be:
static const DroidVTable R2_D2_Droid_impl = {
.name = R2_D2_name,
.turn_on = R2_D2_turn_on,
};Please, note that you have to specify () for the *_CUSTOM attribute; do not leave it empty.
Having a well-defined semantics of the macros, you can write an FFI which is quite common in C.
…Note: shortened vs. postfixed versions
Each listed identifier in the above grammar corresponds to a macro name defined by default -- these are called shortened versions. On the other hand, there are also postfixed versions (interface99, impl99, vfunc99, etc.), which are defined unconditionally. If you want to avoid name clashes caused by shortened versions, define IFACE99_NO_ALIASES before including interface99.h. Library headers are strongly advised to use the postfixed macros, but without resorting to IFACE99_NO_ALIASES.
Notes:
_IFACE mNo open issues yet, or sync has not completed.