No, C is limited because it's mutually exclusive: either encapsulation, or zero overhead by-value passing. Other languages, like C++ or Rust, allow both at the same time.
No, C is limited because it's mutually exclusive: either encapsulation, or zero overhead by-value passing. Other languages, like C++ or Rust, allow both at the same time.
In Modula-2, I can specify an API in its DEFINITION module, and after compiling it, client applications can use such an API without the implementation being ready yet, and still I can compile the client and check if it is free of syntax errors.
> 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.
Specially great in IoT instead of macros accessing directly IO ports.