Skip to content

friendlyanon/generate-opaque-structs

Repository files navigation

generate-opaque-structs

This project was generated by cmake-init.
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 and CheckTypeAlign 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.

About

Example to show how to generate opaque structs with proper size and alignment

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published