d-unsed / ruru

Native Ruby extensions written in Rust
MIT License
832 stars 40 forks source link

Documentation missing: How to wrap a struct with lifetime? #63

Open matthiasbeyer opened 7 years ago

matthiasbeyer commented 7 years ago

I have a struct with a lifetime:

pub struct Foo<'a> {
    // ...
}

How to wrap that?

matthiasbeyer commented 7 years ago

So it seems like this is not possible. What I did to ship around this issue is introducing a (static) cache where objects are fetched again and again from, so I do not run into a lifetime issue.

This is a clumsy solution, but it works for me. The result can be seen here: https://github.com/matthiasbeyer/imag/pull/847. By now it works fine and I hope it will work with my bindings. They are almost finished (the first step towards a full-featured ruby binding for my libraries at least, not the complete bindings).

d-unsed commented 7 years ago

Hey @matthiasbeyer!

Yes, ruru does not support structs with lifetimes for now and I haven't found a way to easily implement this.

On the other hand, if a struct has a lifetime, it has a reference to another Rust object. When a struct is moved to a Ruby object with wrap_data, it kinda leaves Rust world and moves to a Ruby world until ruru fetches it back with get_data. During that period of time the object which is referenced by current struct, can be freed and borrow checker cannot guarantee that. That's why I believe only structs with 'static lifetimes can be wrapped with wrap_data, though I will need to check this.

matthiasbeyer commented 7 years ago

Jup, I basically confirmed what you said there. I'm implementing around this restriction, which also applies to other languages... so if you move things from Rust to C, Cpp, Ruby, Python,... basically every other language, you have to make sure things are handled correctly.

I'm closing this here, as I am working on a solution for my specific problem here: https://github.com/matthiasbeyer/imag/pull/942