给你:
use std::io::Read;
use std::mem;
use std::slice;
#[repr(C, packed)]
#[derive(Debug, Copy, Clone)]
struct Configuration {
item1: u8,
item2: u16,
item3: i32,
item4: [char; 8],
}
const CONFIG_DATA: &[u8] = &[
0xfd,
0xb4, 0x50,
0x45, 0xcd, 0x3c, 0x15,
0x71, 0x3c, 0x87, 0xff,
0xe8, 0x5d, 0x20, 0xe7,
0x5f, 0x38, 0x05, 0x4a,
0xc4, 0x58, 0x8f, 0xdc,
0x67, 0x1d, 0xb4, 0x64,
0xf2, 0xc5, 0x2c, 0x15,
0xd8, 0x9a, 0xae, 0x23,
0x7d, 0xce, 0x4b, 0xeb,
];
fn main() {
let mut buffer = CONFIG_DATA;
let mut config: Configuration = unsafe { mem::zeroed() };
let config_size = mem::size_of::<Configuration>();
unsafe {
let config_slice = slice::from_raw_parts_mut(&mut config as *mut _ as *mut u8, config_size);
buffer.read_exact(config_slice).unwrap();
}
println!("Read structure: {:#?}", config);
}
在这里试试(已更新至 Rust 1.38)
然而,需要注意的是,不安全的代码是不安全的。在 slice::from_raw_parts_mut()
调用后,同时存在两个可变句柄引用同一数据,这违反了 Rust 的别名规则。因此,您应该尽可能短地保留从结构创建的可变切片。我还假设您知道字节序问题 - 上面的代码绝不是可移植的,并且如果在不同类型的机器上编译和运行将返回不同的结果(例如 ARM vs x86)。
如果您可以选择格式并希望使用紧凑的二进制格式,请考虑使用bincode。否则,如果需要解析某些预定义的二进制结构,byteorder crate 是正确的方式。