Tim*_*mmm 3 ffi rust lifetime-scoping
我正在包装一个C库,它有一个标准的上下文对象:
library_context* context = library_create_context();
Run Code Online (Sandbox Code Playgroud)
然后使用它可以创建更多对象:
library_object* object = library_create_object(context);
Run Code Online (Sandbox Code Playgroud)
并摧毁他们两个:
library_destroy_object(object);
library_destroy_context(context);
Run Code Online (Sandbox Code Playgroud)
所以我把它包装在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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
所以现在我可以做到这一点,它似乎工作:
fn main() {
let mut ctx = Context::new();
let ob = ctx.create_object();
}
Run Code Online (Sandbox Code Playgroud)
但是,我也可以这样做:
fn main() {
let mut ctx = Context::new();
let ob = ctx.create_object();
drop(ctx);
do_something_with(ob);
}
Run Code Online (Sandbox Code Playgroud)
即,库对象在它创建的对象之前被销毁.
我可以以某种方式使用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);
}
Run Code Online (Sandbox Code Playgroud)
这将失败
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
Run Code Online (Sandbox Code Playgroud)
有时人们喜欢使用PhantomData,但我不确定我在这里看到了什么好处:
fn create_object(&mut self) -> Object {
Object {
marker: PhantomData,
raw_object: 1,
}
}
#[derive(Debug)]
struct Object<'a> {
marker: PhantomData<&'a ()>,
raw_object: u8,
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
241 次 |
| 最近记录: |