我正在包装一个C库,它具有标准的上下文对象:
library_context* context = library_create_context();
然后使用它可以创建更多对象:
library_object* object = library_create_object(context);
并将其销毁:
library_destroy_object(object);
library_destroy_context(context);
所以我已经将其包裹在生锈结构中:
struct Context {
raw_context: *mut library_context,
}
impl Context {
fn new() -> Context {
Context {
raw_context: unsafe { library_create_context() },
}
}
fn create_object(&mut self) -> Object {
Object {
raw_object: unsafe { library_create_object(self.raw_context) },
}
}
}
impl Drop for Context {
fn drop(&mut self) {
unsafe {
library_context_destroy(self.raw_context);
}
}
}
struct Object {
raw_object: *mut library_object,
}
impl Drop for Object {
fn drop(&mut self) {
unsafe {
library_object_destroy(self.raw_object);
}
}
}
所以现在我可以做到这一点,而且似乎有效:
fn main() {
let mut ctx = Context::new();
let ob = ctx.create_object();
}
但是,我也可以这样做:
fn main() {
let mut ctx = Context::new();
let ob = ctx.create_object();
drop(ctx);
do_something_with(ob);
}
即。在其创建的对象为之前,库上下文被破坏。
我可以以某种方式使用Rust的终身系统来防止上述代码编译?
是的,只需使用普通寿命:
#[derive(Debug)]
struct Context(u8);
impl Context {
fn new() -> Context {
Context(0)
}
fn create_object(&mut self) -> Object {
Object {
context: self,
raw_object: 1,
}
}
}
#[derive(Debug)]
struct Object<'a> {
context: &'a Context,
raw_object: u8,
}
fn main() {
let mut ctx = Context::new();
let ob = ctx.create_object();
drop(ctx);
println!("{:?}", ob);
}
这将失败
error[E0505]: cannot move out of `ctx` because it is borrowed
--> src/main.rs:26:10
|
25 | let ob = ctx.create_object();
| --- borrow of `ctx` occurs here
26 | drop(ctx);
| ^^^ move out of `ctx` occurs here
有时人们喜欢使用PhantomData
,但我不确定我在这里看到好处:
fn create_object(&mut self) -> Object {
Object {
marker: PhantomData,
raw_object: 1,
}
}
#[derive(Debug)]
struct Object<'a> {
marker: PhantomData<&'a ()>,
raw_object: u8,
}