将结构强制转换为数组是否合法

问题描述 投票:1回答:1

考虑以下内容

// Just a sequence of adjacent fields of same the type
#[repr(C)]
#[derive(Debug)]
struct S<T> {
    a : T,
    b : T,
    c : T,
    d : T,
}

impl<T : Sized> S<T> {
    fn new(a : T, b : T, c : T, d : T) -> Self {
        Self {
            a,
            b,
            c,
            d,
        }
    }
    // reinterpret it as an array
    fn as_slice(&self) -> &[T] {
        unsafe { std::slice::from_raw_parts(self as *const Self as *const T, 4) }
    }
}

fn main() {
    let s = S::new(1, 2, 3, 4);

    let a = s.as_slice();

    println!("s :: {:?}\n\
              a :: {:?}", s, a);
}
  • 此代码可移植吗?
  • 假定具有相同类型字段的repr(C)结构可以像数组一样被重新解释总是安全吗?为什么?
rust slice unsafe memory-layout object-model
1个回答
0
投票

是的,它既安全又便携。 std::slice::from_raw_parts的文档的安全性部分中列出的要点在这里都无所谓。

© www.soinside.com 2019 - 2024. All rights reserved.