Precise memory layout control in Rust?

后端 未结 3 1764
野趣味
野趣味 2021-02-03 22:14

As far as I know, the Rust compiler is allowed to pack, reorder, and add padding to each field of a struct. How can I specify the precise memory layout if I need it?

In

3条回答
  •  误落风尘
    2021-02-03 23:17

    There's no longer to_uint. In Rust 1.0, the code can be:

    #[repr(C, packed)]
    struct Object {
        a: i8,
        b: i16,
        c: i32, // other members
    }
    
    fn main() {
        let obj = Object {
            a: 0x1a,
            b: 0x1bbb,
            c: 0x1ccccccc,
        };
    
        let base = &obj as *const _ as usize;
        let a_off = &obj.a as *const _ as usize - base;
        let b_off = &obj.b as *const _ as usize - base;
        let c_off = &obj.c as *const _ as usize - base;
    
        println!("a: {}", a_off);
        println!("b: {}", b_off);
        println!("c: {}", c_off);
    }
    

提交回复
热议问题