问题描述
我有一个未知大小的字节缓冲区,并且我想创建一个指向该缓冲区开头的内存的局部struct变量。遵循在C语言中所做的事情,我在Rust中尝试了很多不同的操作,并不断出错。这是我最近的尝试:
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 tried a lot of different things in Rust and kept getting errors. This is my latest attempt:
use std::mem::{size_of, transmute};
#[repr(C, packed)]
struct MyStruct {
foo: u16,
bar: u8,
}
fn main() {
let v: Vec<u8> = vec![1, 2, 3];
let buffer = v.as_slice();
let s: MyStruct = unsafe { transmute(buffer[..size_of::<MyStruct>()]) };
}
我收到一个错误:
error[E0277]: the size for values of type `[u8]` cannot be known at compilation time
--> src/main.rs:12:42
|
12 | let s: MyStruct = unsafe { transmute(buffer[..size_of::<MyStruct>()]) };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `[u8]`
= note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
推荐答案
如果您不想将数据复制到结构,但可以将其保留在适当的位置,可以使用。而是创建& MyStruct
:
If you don't want to copy the data to the struct but instead leave it in place, you can use slice::align_to
. This creates a &MyStruct
instead:
#[repr(C, packed)]
#[derive(Debug, Copy, Clone)]
struct MyStruct {
foo: u16,
bar: u8,
}
fn main() {
let v = vec![1u8, 2, 3];
// I copied this code from Stack Overflow
// without understanding why this case is safe.
let (head, body, _tail) = unsafe { v.align_to::<MyStruct>() };
assert!(head.is_empty(), "Data was not aligned");
let my_struct = &body[0];
println!("{:?}", my_struct);
}
在这里,使用 align_to $是安全的c $ c>将某些字节转换为
MyStruct
,因为我们已使用 repr(C,packed)
和所有 MyStruct
中的类型可以是任意字节。
Here, it's safe to use align_to
to transmute some bytes to MyStruct
because we've used repr(C, packed)
and all of the types in MyStruct
can be any arbitrary bytes.
另请参见:
- How to read a struct from a file in Rust?
- Can I take a byte array and deserialize it into a struct?
这篇关于将u8缓冲区转换为Rust中的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!