我正在封装一个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的生命周期系统来防止上面的代码编译?