I need to declare a C struct in my Rust code which needs to be 1-byte aligned. How do I declare it? I've heard that #[repr(packed)]
is not recommended.
AFAIK, packed(N)
is the only (current, nightly only) way to align down. Where did you hear it's not recommended? Or rather, it's likely not recommended to create unaligned structs in general but if you do, I think this is the only way.
Heard from a colleague and then saw this: https://github.com/rust-lang/rust/issues/27060. I admit I didn't read the issue fully (the discussion was a bit beyond the ken of my knowledge as well).
How do you intend to use this struct on the Rust side?
I will be reading some of the fields. I don't intend to create the struct in Rust. Some C function will create it for me. I don't intend to write to any of the fields. I won't be doing any reinterpret casts on the fields either.
From your description, I probably would just use read unaligned and pointer offsets rather than trying to make a structure.
That's interesting . I could use it, but it'll be more ergonomic certainly if I can access through a declared struct.
I think if you’re going to be only reading from a raw ptr, then repr(packed) should be ok. That’s my reading of the linked issue around repr packed causing UB under some circumstances.