This is by far the best article I've seen on the subject in terms of simplicity and explaining quickly what it means to have a
#[repr(C)]
annotation on types.The most eye opening bit are the visuals, with first the C representation. Notice how there's extra padding, to ensure everything is byte-aligned. Consider,
#[repr(C)]
struct Foo {
tiny: bool,
normal: u32,
small: u8,
long: u64,
short: u16,
}
- tiny: single byte, padded to 4 bytes so as to be byte-aligned. It's surprising that we are wasting 3-bytes and 7-bits to represent 1 bit!!
- small: This is a single byte, but since the struct's largest value stored is a long (u64), which needs 8-bytes, this is padded as 1 byte + 7 bytes of padding.
See rest of Christopher's article for details on rest of the struct fields.
and Rust's default representation
This was a great read, and hope you enjoyed it as well.