2.0 KiB
2.0 KiB
RAII and defer macros for C
What?
Basically you can get everything apart nasty inheritance hiercheries:
- Good perf post-OOP with structs, "methods" constructors, destructors
- RAII for your resources (not just memory)
- zig-style defer
- no dependencies, just defer.h and handle.h (or just one if you need both)
Examples
Zig-style defer:
#include "defer.h"
...
void *ram = malloc(n);
defer {
free(ram);
printf("%d bytes freed\n", n);
};
C++ / Rust style constructor and destructor:
#include "handle.h"
struct Vektor {
int count;
int *v;
}; handle(Vektor) {
switch(state) {
case HANDLE_CREAT:
self->count = *(int*) data;
self->v = (int*) calloc(self->count, sizeof(int));
break;
case HANDLE_DESTR:
if(self->v) free(self->v);
break;
}
}
RAII (with scope closing destructors in reverse order):
int n; scanf(" %d", n);
creat(Vektor, data, &n);
printf("data.count:%d\n", data.count);
Generics
Generic array using handle.h
#include <stdlib.h>
#include "handle.h"
/* Generic array macro */
#define Array(T,AT) struct AT { \
size_t count; \
T *v; \
}; handle(AT) { \
if(state == HANDLE_CREAT) { \
self->count = *(size_t*) data; \
self->v = (T*) calloc(self->count, sizeof(T)); \
} else if (state == HANDLE_DESTR){ \
if(self->v) free(self->v); \
} \
}
Usage:
#include "array.h"
Array(uint64_t, Array_uint64);
int main() {
size_t n = 0;
printf("Number of elements to sum: ");
scanf(" %zu", &n);
/* Create a 64 bit array of 'n' elements named 'data' */
creat(Array_uint64, data, &n);
...
}
Compatibility
Ok this might be pain for you but this works only with gcc... At least it also works with C++ compilers so you can share your C codes later with C++.
LICENCE
CC-BY