Skip to content

Instantly share code, notes, and snippets.

@torkleyy
Created March 31, 2018 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save torkleyy/ae279faf5c5823e54cf39cc4268ebe7d to your computer and use it in GitHub Desktop.
Save torkleyy/ae279faf5c5823e54cf39cc4268ebe7d to your computer and use it in GitHub Desktop.
[USE WITH CAUTION, not reviewed] How the compiler drops trait objects in Rust
use std::ptr::write;
#[derive(Clone, Copy, Debug)]
#[repr(C)]
struct FatPtr {
ptr: *mut (),
extra: *const (),
}
trait Foo {
}
struct Bar(usize);
impl Foo for Bar {
}
impl Drop for Bar {
fn drop(&mut self) {
println!("Bar!");
}
}
unsafe fn _dyn(foo: *mut Foo) {
let fat = *(&foo as *const _ as *const FatPtr);
let vtable = fat.extra as *const fn(*mut ()); // is this using the Rust ABI?
(*vtable)(fat.ptr);
}
fn main() {
let mut dst = [0usize; 1];
unsafe {
write(&mut dst as *mut _ as *mut Bar, Bar(5));
_dyn(&mut dst as *mut _ as *mut Bar as *mut Foo);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment