【发布时间】:2022-11-30 22:15:54
【问题描述】:
存储生命周期绑定对象(通过原始指针)以供将来 FFI 调用使用是否有效?
这是一个最小的示例:
struct X(u32);
struct Data<'a> {
x: &'a mut X,
}
fn create(x: &mut X) -> Data<'_> {
Data { x }
}
fn main() {
// Our referenced object, guaranteed not to be destroyed during FFI calls
let mut x = X(42);
// First FFI call (just a normal call for this sample)
let ptr = {
let xref = &mut x; // start of 'a
let data = create(xref);
Box::into_raw(Box::new(data))
// end of 'a
};
// ptr is returned to the C world
// Next FFI call, convert the raw pointer back
let data = unsafe { Box::from_raw(ptr) };
// data stores a field having type &'a mut X
// but the lifetime of the reference it holds ('a) has theoretically expired
// even if X is guaranteed to still be alive
// This "works", but is it valid?
dbg!(data.x.0);
}
假设我们可以保证:
-
x对所有 FFI 调用有效(因此引用始终指向有效对象) - 无法从安全 Rust 获得对
x的 2 个引用
代码有效吗?
或者引用生命周期的“到期”是否足以使代码无效?如果是这样,是否可以证明这一点(例如通过产生内存损坏)?
【问题讨论】: