-
-
Save NocturnDragon/ada1d95dab8b497540acf2923d0fe139 to your computer and use it in GitHub Desktop.
Local opaque object in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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