How to Create Unaligned Struct (for FFI)


#1

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.


#2

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.


#3

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).


#4

How do you intend to use this struct on the Rust side?


#5

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.


#6

From your description, I probably would just use read unaligned and pointer offsets rather than trying to make a structure.


#7

That’s interesting :+1:. I could use it, but it’ll be more ergonomic certainly if I can access through a declared struct.


#8

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.