I want to understand how the virtual table works and possibly use it in the future. I know that DST pointers are fat pointers (usize, usize), where the first pointer is data and the second pointer is virtual table. I was able to get the data by the pointer, but apparently it didn’t work out to get the pointer to the virtual table, because from https://docs.google.com/presentation/d/1q-c7UAyrUlM-eZyTo1pd8SZ0qwA_wYxmPZVOQkoDmH4/edit#slide=id.p the size of the structure should be stored by the pointer in the size variable from the code below, but it is not. Perhaps I do not understand correctly how the virtual table is stored?
My code:
#![feature(pointer_byte_offsets)]
trait MyRule {
fn some_method1(&self) {}
fn some_method2(&self) {}
}
struct MyData {
data: u32,
}
impl MyRule for MyData {}
fn main() {
unsafe {
let b: Box<dyn MyRule> = Box::new(MyData { data: 5 });
let fat_ptr = Box::into_raw(b);
dbg!(*(fat_ptr.cast::<u32>())); // data = 5
let vtbl_ptr = fat_ptr.byte_add(8).cast::<*mut usize>();
let destructor_ptr = (*vtbl_ptr).cast::<usize>();
let size = destructor_ptr.byte_add(8);
dbg!(size);
dbg!(*size); // Not size!!!
}
}
I think that the problem is that I'm not getting the pointer to the table itself correctly. So what's the right way to do this, and how do you access table elements?