I'm working with an ABI, where I need exact control over the data layout of the payload on both ends. #[repr(C)]
already helps a lot. Furthermore, there should be no padding between fields at all, ever. Additionally, the beginning of the payload should be page-aligned.
Rust has the modifiers #[repr(packed(N))]
and #[repr(align(N))]
, both compatible with repr(C)
, but they can't be used together. With #[repr(C, packed(4096))]
I can't achieve, what I want. How to solve this?
The packed(N)
type layout modifier is no guarantee, that there will be never padding at all. This is only the case for packed
/ packed(1)
. This is so because packed(N)
in fact can only lower the alignment of each field to min(N, default alignment)
. packed(N)
doesn't mean, that the struct is "packed", ie no padding at all between fields, or the alignment of the struct is 4096 byte.
If you want a page-aligned struct with no padding at all, in fact, you want to do the following:
#[repr(align(4096))]
struct Aligned4096<T>(T);
// plus impl convenient methods
#[repr(C, packed)]
struct Foo {
a: u8,
b: u64,
c: u16,
d: u8,
}
// plus impl convenient methods
fn main() {
let aligned_foo = Aligned4096(Foo::new());
}
A more detailed view how different N in packed(N)
change the type layout, is shown in this can find a nice table here . More information about the type layout modifiers, in general, is provided in the official language documentation .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.