可以在稳定的编译器上控制 Rust 结构对齐吗?
Can Rust struct alignment be controlled on the stable compiler?
我想使用 aligned
属性为 C 结构编写 Rust FFI。
在夜间,可以像 一样使用 #[feature(repr_simd)]
。没有 #[repr(simd)]
的相同技术似乎仅限于 8 个字节的最大对齐。
对齐和 SIMD 都有各种问题和 RFC 开放,编译器指向 tracking issue #27731 似乎已停滞。
RFC #325 很明确地指向了 no,但它有点老了。
从 1.22 版开始,使用纯(不安全?)Rust 的稳定编译器是否可以做到这一点?
到目前为止,答案是肯定的,您可以在稳定的 Rust 中指定类型的对齐方式。这是 stabilized in 1.25.0. 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>());
}
我想使用 aligned
属性为 C 结构编写 Rust FFI。
在夜间,可以像 #[feature(repr_simd)]
。没有 #[repr(simd)]
的相同技术似乎仅限于 8 个字节的最大对齐。
对齐和 SIMD 都有各种问题和 RFC 开放,编译器指向 tracking issue #27731 似乎已停滞。
RFC #325 很明确地指向了 no,但它有点老了。
从 1.22 版开始,使用纯(不安全?)Rust 的稳定编译器是否可以做到这一点?
到目前为止,答案是肯定的,您可以在稳定的 Rust 中指定类型的对齐方式。这是 stabilized in 1.25.0. 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>());
}