I wonder whether the following code using mem::transmute
is safe.
A snippet using mem::transmute
(on play.rust-lang.org).
use std::mem;
use std::sync::Arc;
#[derive(Debug)]
struct B {}
#[derive(Debug)]
struct C {
b: B,
}
#[derive(Debug)]
struct A<'b> {
b: &'b B,
}
#[derive(Debug)]
struct SafeContainer {
c: Arc<C>,
unsafe_a: A<'static>,
}
impl SafeContainer {
fn new<'b>(c: &'b Arc<C>, a: A<'b>) -> Self {
SafeContainer {
c: c.clone(),
unsafe_a: unsafe { mem::transmute(a) },
}
}
fn a<'b>(&'b self) -> &A<'b> {
unsafe { mem::transmute(&self.unsafe_a) }
}
}
pub fn main() {
let c = Arc::new(C { b: B {} });
let a = A { b: &c.b };
let container = SafeContainer::new(&c, a);
drop(c);
// do something with `container.a()`...
println!("{:?}", container.a());
drop(container);
}
I am trying to write Python bindings to a Rust crate of mine using PyO3. To this end, I have to somehow encapsulate structs with lifetime parameter inside a Python object whose corresponding struct must not have any lifetime parameters. So, I had the idea to extend the lifetime to 'static
using mem::transmute
and make sure that I keep an Arc
owning the data around.
Is this a sound idea or is there a better way of doing this?