Created
March 31, 2018 14:18
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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