限制Rust中的对象生命周期

时间:2016-12-13 20:59:59

标签: rust ffi lifetime-scoping

我正在包装一个C库,它有一个标准的上下文对象:

library_context* context = library_create_context();

然后使用它可以创建更多对象:

library_object* object = library_create_object(context);

并摧毁他们:

library_destroy_object(object);
library_destroy_context(context);

所以我把它包装在Rust结构中:

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的生命周期系统来阻止上面的代码编译吗?

1 个答案:

答案 0 :(得分:5)

是的,只需使用正常的生命周期:

#[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,
}