FAQ - Help and questions

How do C structs, unions and enums map to Rust, and when does layout matter?

#porting#c-language#ffipublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

A C struct becomes a Rust struct, but Rust may reorder the fields unless you add repr(C), which you need whenever C code reads the same memory. A C union with a tag field becomes a Rust enum with data, and a C enum of numbers becomes an enum with explicit values.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

Inside a pure Rust program you do not care how a struct is laid out in memory. At a boundary with C, a file format or the network you do: both sides must agree on the order, size and padding of the fields.

By default Rust is free to reorder the fields of a struct to reduce padding, so the layout is not stable. #[repr(C)] fixes the layout to what a C compiler for the same target would produce. The program prints the size and field offsets of the same three-field struct in both forms, compares a C union with a Rust enum, and shows the size of pointer-like types. It was compiled and run with rustc 1.93.0 on a 64-bit Windows target.

src/main.rsrust
use std::mem::{align_of, offset_of, size_of};

// C:  struct header { uint8_t kind; uint32_t len; uint16_t flags; };
#[repr(C)]
struct HeaderC {
    kind: u8,
    len: u32,
    flags: u16,
}

// Without repr(C) the compiler may reorder the fields to waste less space.
struct HeaderRust {
    kind: u8,
    len: u32,
    flags: u16,
}

// C:  union value { int32_t i; float f; };   used with a separate "which one is it" field
#[repr(C)]
union Value {
    i: i32,
    f: f32,
}

// Rust: the tag and the data travel together, and match checks the tag.
enum Tagged {
    Int(i32),
    Float(f32),
}

fn main() {
    println!("HeaderC: size {} align {} offsets kind {} len {} flags {}", size_of::<HeaderC>(), align_of::<HeaderC>(), offset_of!(HeaderC, kind), offset_of!(HeaderC, len), offset_of!(HeaderC, flags));
    println!("HeaderRust: size {}", size_of::<HeaderRust>());

    let v = Value { f: 1.0 };
    // SAFETY: both fields are 4-byte plain numbers, so reading the bits as i32 is allowed.
    println!("bits of 1.0f32: {:#x}", unsafe { v.i });
    let _ = Value { i: 7 };

    for t in [Tagged::Int(7), Tagged::Float(2.5)] {
        match t {
            Tagged::Int(i) => println!("int {i}"),
            Tagged::Float(f) => println!("float {f}"),
        }
    }
    println!("size of Tagged {} ; Option<Box<u8>> {} ; Box<u8> {}", size_of::<Tagged>(), size_of::<Option<Box<u8>>>(), size_of::<Box<u8>>());
}
text
HeaderC: size 12 align 4 offsets kind 0 len 4 flags 8
HeaderRust: size 8
bits of 1.0f32: 0x3f800000
int 7
float 2.5
size of Tagged 8 ; Option<Box<u8>> 8 ; Box<u8> 8

What the numbers say. With repr(C) the fields keep their declared order, so len starts at offset 4 (after padding behind the one-byte kind) and flags at 8, and the struct is padded to 12 bytes. The default layout needs only 8 bytes, which is Rust's reordering at work; the exact result is a property of this compiler version, not a promise, so never depend on it.

The union can be read as either field only inside unsafe, and nothing tells you which field is the valid one. The enum stores a tag and the data together (8 bytes here: a tag plus a 4-byte payload, padded to the payload's alignment), and match cannot read the wrong variant. Option<Box<u8>> is the same size as Box<u8>: the compiler uses the null pointer as None, which is why Option replaces nullable pointers at no cost.

How to do it#

  1. Struct only used inside Rust: no attribute needed. Struct that C reads or writes, or that is written to a file or socket as raw bytes: #[repr(C)], with fields of fixed-width types (u32, not usize).
  2. A C enum with numeric values that C code compares: #[repr(C)] enum Kind { A = 0, B = 1 } for passing by value across the boundary. Receiving an arbitrary integer from C and converting it to such an enum without checking is undefined behaviour if the value is not one of the listed variants; take an integer type in the signature and convert with a match or TryFrom.
  3. A C tagged union (a union plus a kind field): port the logic as a Rust enum with data. Convert from and to the C layout only at the boundary.
  4. Bit fields have no direct Rust equivalent: store the integer and use masks and shifts, in small methods.
  5. Packed structs (#pragma pack): #[repr(C, packed)], and do not take references to its fields (read them by value).

Common mistakes#

  • Casting a byte buffer to a struct pointer and reading it. Alignment and endianness can differ; parse the fields from bytes explicitly (u32::from_le_bytes).
  • Relying on the default layout in a file format or protocol.
  • Treating a union as a convenience for "type punning" in ordinary code. Use f32::to_bits and from_bits for the example above.

Can I print the offsets of a C struct to compare with Rust?#

Yes. offset_of!(Type, field) is in the standard library. Compare against the offsets the C compiler reports for the same struct on the same target.

What about a flexible array member at the end of a C struct?#

It has no direct equivalent in safe Rust. Treat the header as a struct and the trailing data as a separate slice you create from the pointer and a length.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet