【发布时间】:2020-09-26 02:57:30
【问题描述】:
考虑以下几点:
// 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