https://github.com/friendlyanon/generate-opaque-structs
Example to show how to generate opaque structs with proper size and alignment
https://github.com/friendlyanon/generate-opaque-structs
Last synced: 12 days ago
JSON representation
Example to show how to generate opaque structs with proper size and alignment
- Host: GitHub
- URL: https://github.com/friendlyanon/generate-opaque-structs
- Owner: friendlyanon
- Created: 2022-01-28T13:57:46.000Z (almost 4 years ago)
- Default Branch: master
- Last Pushed: 2022-01-29T04:22:06.000Z (almost 4 years ago)
- Last Synced: 2025-03-11T08:12:52.472Z (10 months ago)
- Language: CMake
- Size: 6.84 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# generate-opaque-structs
This project was generated by [cmake-init][1].
It's heavily stripped down to focus on showing how to create opaque structs
that preserve value semantics.
This project makes use of the [CheckTypeSize][2] and [CheckTypeAlign][3] CMake
modules to get the size and alignment of the implementation specific struct,
and creates an opaque struct using those parameters.
Doing this will allow the consumers of an API to not be forced to allocate
these structs on the heap, but instead put them on the stack like normal
values. They will not be able to observe the struct's state, because all they
will see is a byte buffer in the struct exposed to them.
Note that this project requires C11 to be able to use the `_Alignas` keyword,
but a developer crafty enough could make this work just as well with earlier
standards. I can only think of having a buffer of size `x_SIZE + 2 * x_ALIGN`
and the user facing functions do some pointer arithmetic to snap the incoming
pointer to a valid alignment within that buffer before casting it to a pointer
to the implementation. However, `(u)intptr_t` was added in C99 as an optional
feature, so that pointer arithmetic would be cumbersome and non-portable.
[1]: https://github.com/friendlyanon/cmake-init
[2]: https://cmake.org/cmake/help/latest/module/CheckTypeSize.html
[3]: https://github.com/friendlyanon/check-type-align