error: `line` does not live long enough (but I know it does)

error: `line` does not live long enough (but I know it does)

我正在尝试对用 C 编写的库进行某种 ffi,但卡住了。这是一个测试用例:

extern crate libc;
use libc::{c_void, size_t};

// this is C library api call
unsafe fn some_external_proc(_handler: *mut c_void, value: *const c_void,
                             value_len: size_t) {
    println!("received: {:?}" , std::slice::from_raw_buf(
             &(value as *const u8), value_len as usize));
}

// this is Rust wrapper for C library api
pub trait MemoryArea {
    fn get_memory_area(&self) -> (*const u8, usize);
}

impl MemoryArea for u64 {
    fn get_memory_area(&self) -> (*const u8, usize) {
        (unsafe { std::mem::transmute(self) }, std::mem::size_of_val(self))
    }
}

impl <'a> MemoryArea for &'a str {
    fn get_memory_area(&self) -> (*const u8, usize) {
        let bytes = self.as_bytes();
        (bytes.as_ptr(), bytes.len())
    }
}

#[allow(missing_copy_implementations)]
pub struct Handler<T> {
    obj: *mut c_void,
}

impl <T> Handler<T> {
    pub fn new() -> Handler<T> { Handler{obj: std::ptr::null_mut(),} }

    pub fn invoke_external_proc(&mut self, value: T) where T: MemoryArea {
        let (area, area_len) = value.get_memory_area();
        unsafe {
            some_external_proc(self.obj, area as *const c_void,
                               area_len as size_t)
        };
    }
}

// this is Rust wrapper user code
fn main() {
    let mut handler_u64 = Handler::new();
    let mut handler_str = Handler::new();

    handler_u64.invoke_external_proc(1u64); // OK
    handler_str.invoke_external_proc("Hello"); // also OK
    loop  {
        match std::io::stdin().read_line() {
            Ok(line) => {
                let key =
                    line.trim_right_matches(|&: c: char| c.is_whitespace());

                //// error: `line` does not live long enough
                // handler_str.invoke_external_proc(key)
            }
            Err(std::io::IoError { kind: std::io::EndOfFile, .. }) => break ,
            Err(error) => panic!("io error: {}" , error),
        }
    }
}

Rust playpen

如果我取消注释循环内的行,我会得到 "line does not live long enough" 错误。事实上,我意识到 Rust 害怕我可以在 Handler 对象内部的某处存储对切片的短期引用,但我很确定我不会,而且我也知道,将指针传递给外部过程是安全的(实际上,内存是在 C 库端立即复制的)。

我有什么办法绕过这个检查吗?

问题是你错误地参数化了你的结构,而你真的想为函数做参数。当您创建当前 Handler 时,该结构将专门用于包含生命周期的类型。但是line的生命周期只是block的生命周期,所以不可能有持续多次循环迭代的Handler的生命周期。

你想要的是将生命周期绑定到函数调用,而不是结构的生命周期。如您所述,如果将生命周期放在结构上,则该结构能够存储该长度的引用。你不需要那个,所以把通用类型放在函数上:

impl Handler {
    pub fn new() -> Handler { Handler{obj: std::ptr::null_mut(),} }

    pub fn invoke_external_proc<T>(&mut self, value: T) where T: MemoryArea {
        let (area, area_len) = value.get_memory_area();
        unsafe {
            some_external_proc(self.obj, area as *const c_void,
                               area_len as size_t)
        };
    }
}

修改后的答案

既然你想特化一个类型的结构,但不太关心类型的生命周期,让我们试试这个:

#[allow(missing_copy_implementations)]
pub struct Handler<T: ?Sized> {
    obj: *mut c_void,
}

impl<T: ?Sized> Handler<T> {
    pub fn new() -> Handler<T> { Handler{ obj: std::ptr::null_mut() } }

    pub fn invoke_external_proc(&mut self, value: &T) where T: MemoryArea {
        let (area, area_len) = value.get_memory_area();
        unsafe {
            some_external_proc(self.obj, area as *const c_void,
                               area_len as size_t)
        };
    }
}

在这里,我们允许类型未调整大小。由于您不能将未调整大小的值作为参数传递,因此我们现在必须取而代之。我们还必须更改 impl:

impl MemoryArea for str {
    fn get_memory_area(&self) -> (*const u8, usize) {
        let bytes = self.as_bytes();
        (bytes.as_ptr(), bytes.len())
    }
}