如何将结构与指定的字节边界对齐? [英] How can I align a struct to a specifed 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 thorough 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);
或具有字段baz
的结构Bar
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屋!