Skip to content

Instantly share code, notes, and snippets.

Created June 6, 2017 20:04
Show Gist options
  • Save anonymous/0936f37c5ed93130773ecb27a3689e7f to your computer and use it in GitHub Desktop.
Save anonymous/0936f37c5ed93130773ecb27a3689e7f to your computer and use it in GitHub Desktop.
Shared via Rust Playground
use std::ops::Deref;
struct Foo {
a: u32
}
impl Foo {
fn bar(&self) {
println!("bar: a={}, address of self={:x}", self.a, self as *const Foo as usize);
}
fn lol(s: &Box<Self>) {
let ptr = s.deref() as *const Foo;
let a = unsafe {(*ptr).a};
println!("lol: a={}, ptr={:x}", a, ptr as usize);
}
}
fn main() {
let a = Box::new(Foo {a: 5});
a.bar();
let ptr = Box::into_raw(a);
println!("ptr: {:x}", ptr as usize);
let b = unsafe { Box::from_raw(ptr) };
Foo::lol(&b);
b.bar();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment