raw::TraitObject


#1

I am trying to build a raw::TraitObject using mem::transmute As suggested by the doc but I am getting a compiler error

Standard Error
   Compiling playground v0.0.1 (file:///playground)
error[E0512]: transmute called with types of different sizes
  --> src/main.rs:18:38
   |
18 | let to : raw::TraitObject = unsafe { mem::transmute(b_foo) };
   |                                      ^^^^^^^^^^^^^^
   |
   = note: source type: std::boxed::Box<FooImpl> (64 bits)
   = note: target type: std::raw::TraitObject (128 bits)

What am I doing weong here ?

Link to a sample playground:
https://play.rust-lang.org/?gist=843a5e055eb665d3d8ac8feef50b2011&version=nightly


#2

transmute called with types of different sizes

Box<FooImpl> is just one pointer, while Box<Foo> and raw::TraitObject are two pointer-wide (pointer to the structure + pointer to the vtable). You have to create Box<Foo> first:

let to: Box<Foo> = Box::new(FooImpl(69)); // Box<FooImpl> coerces to Box<Foo>
let to: raw::TraitObject = unsafe { transumte(to) };

#3

Ah great. Thanks a lot