从Ruby FFI结构返回Mutable Rust结构

时间:2015-07-19 07:36:20

标签: ruby rust ffi

我试图将一个FFI结构传递给Ruby模块生锈,改变结构并将结构传递给ruby模块。

在这种情况下处理生命周期的正确方法是什么?

我遇到了一生的错误:

src/lib.rs:20:55: 20:70 error: missing lifetime specifier [E0106]
src/lib.rs:20 pub extern fn add_one_to_vals(numbers: TwoNumbers) -> &mut TwoNumbers {
                                                                    ^~~~~~~~~~~~~~~
src/lib.rs:20:55: 20:70 help: run `rustc --explain E0106` to see a detailed explanation
src/lib.rs:20:55: 20:70 help: this function's return type contains a borrowed value, but the signature does not say which one of `numbers`'s 0 elided lifetimes it is borrowed from

Rust代码:

pub struct TwoNumbers {
    first: i32,
    second: i32,
}

impl TwoNumbers {
    fn plus_one_to_each(&mut self) -> &mut TwoNumbers {
        self.first = self.first + 1;
        self.first = self.second + 1;
        self
    }
}

#[no_mangle]
pub extern fn add_one_to_vals(numbers: TwoNumbers) -> &mut TwoNumbers {
   numbers.plus_one_to_each()
}

1 个答案:

答案 0 :(得分:3)

您的代码无效,因为您尝试返回对本地变量的引用。当你的函数返回时,局部变量将被销毁,因此如果Rust没有禁止它,引用就会变成悬空。

我不知道您的FFI界面的确切详细信息,但很有可能按值返回结构对您有用:

#[no_mangle]
pub extern fn add_one_to_vals(numbers: TwoNumbers) -> TwoNumbers {
    numbers.plus_one_to_each();
    numbers
}