Transmuting u8 buffer to struct in Rust

后端 未结 3 1329
爱一瞬间的悲伤
爱一瞬间的悲伤 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:44

    You can use methods on raw pointers and functions in std::ptr to directly read/write objects in place.

    • std::ptr::read
    • std::ptr::read_unaligned
    • std::ptr::write
    • std::ptr::write_unaligned

    In your case:

    fn main() {
        let v: Vec = vec![1, 2, 3];
        let s: MyStruct = unsafe { std::ptr::read(v.as_ptr() as *const _) };
        println!("here is the struct: {:?}", s);
    }
    

    I would encourage you to wrap this in a reusable method and perform a length check on the source buffer before attempting the read.

提交回复
热议问题