如何将结构与指定的字节边界对齐? [英] How can I align a struct to a specified byte boundary?
问题描述
我需要将结构与 Rust 中的 16 字节边界对齐.似乎可以通过 repr
属性,但它不支持这个确切的用例.
I need to align a struct to a 16 byte boundary in Rust. It seems possible to give hints about alignment through the repr
attribute, but it doesn't support this exact use case.
我试图实现的功能测试是一个类型 Foo
使得
A functional test of what I'm trying to achieve is a type Foo
such that
assert_eq!(mem::align_of::<Foo>(), 16);
或者,一个结构体 Bar
带有一个字段 baz
使得
or alternatively, a struct Bar
with a field baz
such that
println!("{:p}", Bar::new().baz);
总是打印一个能被 16 整除的数字.
always prints a number divisible by 16.
这在 Rust 中目前是否可行?有什么解决办法吗?
Is this currently possible in Rust? Are there any work-arounds?
推荐答案
huon 的回答很好,但是已经过时了.
huon's answer is good, but it's out of date.
从 Rust 1.25.0 开始,您现在可以将类型与 N 对齐
字节使用属性 #[repr(align(N))]
.它记录在 参考的类型布局部分.请注意,对齐必须是 2 的幂,您不能混合 align
和 packed
表示,并且对齐类型可能会为类型添加额外的填充.这是如何使用该功能的示例:
As of Rust 1.25.0, you may now align a type to N
bytes using the attribute #[repr(align(N))]
. It is documented under the reference's Type Layout section. Note that the alignment must be a power of 2, you may not mix align
and packed
representations, and aligning a type may add extra padding to the type. Here's an example of how to use the feature:
#[repr(align(64))]
struct S(u8);
fn main() {
println!("size of S: {}", std::mem::size_of::<S>());
println!("align of S: {}", std::mem::align_of::<S>());
}
这篇关于如何将结构与指定的字节边界对齐?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!