> You can do dummy defines of structs with the same size
Don't forget alignment. The general pattern is: https://godbolt.org/z/6je9Yb3rf.
If you have:
struct foo;
in foo.h and: struct foo {
int a;
double x;
...
};
in foo.c, you won't have sizeof(struct foo) available from bar.c, so your construction won't work in bar.c. You could define a function: size_t sizeof_foo(void);
which just returns sizeof(struct foo) from inside foo.c, but since this size is now only known at runtime, you'll need to resort to alloca or VLAs...In the .c file you define private_foo, same a public_foo except that the byte array is replaced with the actual members.
You static assert that size and alignment match and cast at function boundaries.
You hope not to have violated strict aliasing rules.
This is not completely unlike type erasure with small buffer optimization done by some c++ classes like std::function.
The big downside here is that you’re leaking the size of the details into your ABI which wouldn’t happen with a fully opaque type… I could see some uses for it but haven’t felt a strong enough need to reach for it before, although it has occurred to me.