gpt4 book ai didi

data-structures - 将 u8 缓冲区转换为 Rust 中的结构

转载 作者:行者123 更新时间:2023-11-29 07:47:45 24 4
gpt4 key购买 nike

我有一个未知大小的字节缓冲区,我想创建一个指向缓冲区开头内存的本地结构变量。按照我在 C 中所做的,我在 Rust 中尝试了很多不同的东西,但不断出错。这是我最近的尝试:

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>

最佳答案

如果您不想将数据复制到结构中,而是将其保留在原地,您可以使用 slice::align_to .这将创建一个 &MyStruct:

#[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 将一些字节转换为 MyStruct 是安全的,因为我们已经使用了 repr(C, packed) 和所有MyStruct 中的类型可以是任意字节。

另见:

关于data-structures - 将 u8 缓冲区转换为 Rust 中的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42499049/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com