2
votes

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.

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()
}
1
You'll need repr(C) on that struct if it's used across the boundary at all - Steve Klabnik
You may want to read The Rust FFI Omnibus and suggest improvements if they are missing. - Shepmaster

1 Answers

3
votes

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.

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:

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