带有 Box::from_raw() Box::into_raw() 往返的 Rust 指针无效



我在尝试创建一些 FFI 辅助代码时,正在反对这种所谓的简单用法 Box。

此处的示例在与具有字段的结构一起使用时似乎给出了free(): invalid pointer错误。

pub struct Handle(usize);
impl Handle {
pub fn from<T>(obj: T) -> Self {
let boxed = Box::new(obj);
let mut ptr = Box::into_raw(boxed);
Self::from_ptr_mut(&mut ptr)
}
pub fn from_ptr_mut<T>(ptr: &mut T) -> Self {
Self(ptr as *mut T as usize)
}
pub fn to_box<T>(self) -> Box<T> {
let obj: *mut T = self.to_ptr_mut();
unsafe { Box::from_raw(obj) }
}
pub fn to_ptr_mut<T>(self) -> *mut T {
self.0 as *mut T
}
}
#[allow(dead_code)]
struct Crashes { value: u64 }
impl Drop for Crashes {
fn drop(&mut self) {
println!("Crashes dropped");
}
}
fn crashes() {
let t = Crashes { value: 12 };
let a = Handle::from(t);
let b = a.to_box::<Crashes>();
drop(b);
}
struct Works;
impl Drop for Works {
fn drop(&mut self) {
println!("Works dropped");
}
}
fn works() {
let t = Works;
let a = Handle::from(t);
let b = a.to_box::<Works>();
drop(b);
}
fn main() {
works();
crashes();
}

您可以将其粘贴到 https://play.rust-lang.org/中,并查看它如何引发中止并显示错误free(): invalid pointer

drop函数似乎在适当的时间被调用,但指针似乎以某种方式无效

你最终会在这里创建一个双指针:

impl Handle {
pub fn from<T>(obj: T) -> Self {
let boxed = Box::new(obj);
let mut ptr = Box::into_raw(boxed);
Self::from_ptr_mut(&mut ptr)
}
pub fn from_ptr_mut<T>(ptr: &mut T) -> Self {
Self(ptr as *mut T as usize)
}
...
}

Box::into_raw返回一个指针,但随后您获取对该指针的可变引用,并将该地址存储为usize。您应该只使用Box::into_raw返回的*mut T

使用双指针编译的非工作代码的原因是您的from<T>from_ptr_mut<T>可以采用完全不同的T参数。如果我们认为传递给from<T>的类型T是具体类型,那么在这种情况下,您将使用类型为&mut *mut T的参数调用from_ptr_mut<U>(其中U*mut T(。

它应该看起来像这样:

impl Handle {
pub fn from<T>(obj: T) -> Self {
let boxed = Box::new(obj);
let ptr = Box::into_raw(boxed);
Self::from_ptr_mut(ptr)
}
pub fn from_ptr_mut<T>(ptr: *mut T) -> Self {
Self(ptr as usize)
}
...
}

操场上的工作示例。


即使我们处于unsafe领域,您也可以通过使参数T绑定到Handle结构来让编译器为您完成一些工作。这样,将静态阻止您加载与存储不同的类型。

Handle 包含幻像数据的游乐场示例。

在第二个示例中,您不必告诉编译器您要检索a.to_box::<Crashes>()哪个项目,这很好,因为您不能通过指定错误的类型来引入未定义的行为。

最新更新