C structs with bit fields and FFI

Careful -- the relationship between bitfield declaration order and bit order (as seen by the shift operators) depends not only on the compiler, but on the endianness and platform ABI.

I'd suggest linking in a fragment of C code to provide accessors for the bitfields. Anything else is likely to be fragile.

Note that you may also have trouble determining the size and alignment requirements for this struct in a portable way. Different platforms (even using a given compiler) differ in conventions like whether a zero-length (int : 0) bitfield serves as a break that consumes the rest of the current byte/int/etc. If you search for "bit" in GCC's storage layout configuration options you'll find a lot of ways that this can vary. I'm not fluent enough in Rust to suggest a good way of fixing this one, but you might want to expose functions from C that can return the sizeof/alignof, or even let C allocate the struct for you.

Finally, you should consider sending feedback to the library authors. :smile:

3 Likes