Skip to content

Instantly share code, notes, and snippets.

@NocturnDragon
Forked from keebus/local_opaque_object.c
Created July 18, 2018 15:41
Show Gist options
  • Save NocturnDragon/ada1d95dab8b497540acf2923d0fe139 to your computer and use it in GitHub Desktop.
Save NocturnDragon/ada1d95dab8b497540acf2923d0fe139 to your computer and use it in GitHub Desktop.
Local opaque object in C
// library.h -------------------------------------------------------------------
#define opaque(Type) Type; int $sizeof_##Type(void);
#define opaque_impl(Type) int $sizeof_##Type(void) { return sizeof(Type); }
#define local(Type) ((Type *)alloca($sizeof_##Type()))
// foo.h -----------------------------------------------------------------------
typedef struct Foo opaque(Foo);
void foo_set_data(Foo *foo, int data);
int foo_get_data(Foo *foo);
// foo.c -----------------------------------------------------------------------
struct Foo {
int data;
};
opaque_impl(Foo)
void foo_set_data(Foo *foo, int data)
{
foo->data = data;
}
int foo_get_data(Foo *foo)
{
return foo->data;
}
// main.c ---------------------------------------------------------------------
int main()
{
// Allocates an opaque object Foo on the stack.
Foo *foo = local(Foo);
foo_set_data(foo, 42);
return foo_get_data(foo);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment