4

I want to write a Rust FFI for a C struct using the aligned attribute.

On nightly, one can use #[feature(repr_simd)] as in this question. The same technique without #[repr(simd)] appears to be restricted to a maximum alignment of 8 bytes.

There are various issues and RFCs open for both alignment and SIMD, and the compiler points to tracking issue #27731 which seems to be stalled.

RFC #325 points pretty clearly to no, but it is somewhat old.

Is it possible to do this with the stable compiler, in pure (unsafe?) Rust as of version 1.22?

mfarrugi
  • 178
  • 11

1 Answers1

2

As of now, the answer is yes, you may specify a type's alignment in stable Rust. This was 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>());
}
Cornstalks
  • 37,137
  • 18
  • 79
  • 144