我知道答案是“你不应该”......但为了争论,如何should你做吧?
例如,如果您想编写一个替代方案Vec<T>
效果不同。
我发现你可以通过转化来制作“可以编译和运行的东西”* mut T
值转化为u64
并添加到它们中,然后将它们转换回* mut T
并读取指针处的值(参见下面的示例)。它似乎有效,但留下了一些悬而未决的问题:
Will a * mut T
指针总是适合u64
?
Does write()
当数据是任意(即不是托管类型)数据块时,指向不安全指针会触发指针别名问题libc:calloc
?
这仅有效,因为我使用的是原始类型(f64
)。如果这是一个真实的数据对象,我将不得不forget()
首先是对象;但你能简单地write()
a * mut T
进入目标然后快乐地read()
如果类型很复杂并且有子记录,稍后再输出?
这真的是正确的做法吗?看起来非常别扭。我本以为会发现一些不安全的地方ptrtoint()
/ inttoptr()
一对,但我找不到类似的东西。
Example
extern crate libc;
use std::mem::size_of;
use std::ptr::write;
use std::ptr::read;
use std::mem::transmute;
use libc::calloc;
use libc::free;
use libc::c_void;
struct Array {
length: usize,
data: *mut f64,
}
impl Array {
fn new(length: usize) -> Array {
unsafe {
Array {
length: length,
data: calloc(size_of::<f64>(), length) as *mut f64,
}
}
}
fn set(&mut self, offset: usize, value: f64) {
if offset < self.length {
unsafe {
let root: *mut f64 = transmute(transmute::<*mut f64, u64>(self.data) +
(size_of::<f64>() * offset) as u64);
println!("Write: [{:?}] -> {}", root, value);
write(root, value);
}
} else {
println!("Write: Nope: [{}] is out of bounds", offset);
}
}
fn get(&self, offset: usize) -> f64 {
if offset < self.length {
unsafe {
let root: *const f64 = transmute(transmute::<*mut f64, u64>(self.data) +
(size_of::<f64>() * offset) as u64);
let rtn = read::<f64>(root);
println!("Read: [{:?}] -> {}", root, rtn);
return rtn;
}
}
println!("Read: Nope: [{}] is out of bounds", offset);
0.0
}
}
impl Drop for Array {
fn drop(&mut self) {
unsafe {
free(self.data as *mut c_void);
}
}
}
fn main() {
let mut tmp = Array::new(4);
tmp.set(0, 100.5);
tmp.set(1, 101.5);
tmp.set(2, 102.5);
tmp.set(3, 103.5);
tmp.set(4, 104.5);
tmp.get(0);
tmp.get(1);
tmp.get(2);
tmp.get(3);
tmp.get(4);
}
Output
Write: [0x7f04bdc1e080] -> 100.5
Write: [0x7f04bdc1e088] -> 101.5
Write: [0x7f04bdc1e090] -> 102.5
Write: [0x7f04bdc1e098] -> 103.5
Write: Nope: [4] is out of bounds
Read: [0x7f04bdc1e080] -> 100.5
Read: [0x7f04bdc1e088] -> 101.5
Read: [0x7f04bdc1e090] -> 102.5
Read: [0x7f04bdc1e098] -> 103.5
Read: Nope: [4] is out of bounds