简体   繁体   English

从Ruby FFI结构返回Mutable Rust结构

[英]Return Mutable Rust struct from Ruby FFI struct

I am trying to passing in a FFI struct into rust from a Ruby module, mutating the struct and passing back the struct to the ruby module. 我试图将FFI结构从Ruby模块传递到生锈,使结构发生变异,然后将结构传递回ruby模块。

What is the proper way to handle the lifetime in this scenario? 在这种情况下,处理生存期的正确方法是什么?

I am running into an lifetime error: 我遇到了终身错误:

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 code: 锈代码:

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()
}

Your code does not work because you're trying to return a reference to a local variable . 您的代码无效,因为您试图返回对局部变量的引用。 When your function returns, the local variable will be destroyed, so the reference would became dangling if Rust didn't forbid it. 当函数返回时,局部变量将被销毁,因此如果Rust不禁止引用,该引用将变得悬而未决。

I don't know exact details of your FFI interface, but it's very likely that returning the struct by value will work for you: 我不知道您的FFI接口的确切细节,但是按值返回结构很可能对您有用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM