Transmuting u8 buffer to struct in Rust

后端 未结 3 1369
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-31 12:22

I have a byte buffer of unknown size, and I want to create a local struct variable pointing to the memory of the beginning of the buffer. Following what I\'d do in C, I trie

3条回答
  •  没有蜡笔的小新
    2020-12-31 12:45

    I gave up on the transmute stuff. *mut (raw pointers) in Rust are pretty similar to C pointers, so this was easy:

    #[repr(C, packed)] // necessary
    #[derive(Debug, Copy, Clone)] // not necessary
    struct MyStruct {
        foo: u16,
        bar: u8,
    }
    
    fn main() {
        let v: Vec = vec![1, 2, 3];
        let buffer = v.as_slice();
        let mut s_safe: Option<&MyStruct> = None;
        let c_buf = buffer.as_ptr();
        let s = c_buf as *mut MyStruct;
        unsafe {
            let ref s2 = *s;
            s_safe = Some(s2);
        }
        println!("here is the struct: {:?}", s_safe.unwrap());
    }
    

    The unsafe tag there is no joke, but the way I'm using this, I know my buffer is filled and take the proper precautions involving endianness later on.

提交回复
热议问题