rust 读object

use std::mem;
fn print_object(p:&dyn Bird){
	let (data,vtable):(*const usize,*const usize)=unsafe{mem::transmute(p)};
	println!("data :{:p} vtable:{:p}",data,vtable);
	unsafe{
		println!("data in vtable:{} {} {} {} {}",*vtable,*vtable.offset(1),
			*vtable.offset(2),*vtable.offset(3),*vtable.offset(4));
		println!("data in data:{:x} {} {} {} {} "  ,*data,*data.offset(1),
			*data.offset(2),*data.offset(3),*data.offset(4));

	}
}
trait Bird{
	fn fly(&self);
}
struct Duck{x:i64}
struct Swan{y:u32}
impl Bird for Duck{
	fn fly(&self){
		println!("{}",self.x);
	}
}
impl Bird for Swan{
	fn fly(&self){
		println!("{}",self.y);
	}
}
fn main(){
	let duck=Duck{x:1};
	let swan=Swan{y:2};
	let p_duck=&duck;
	let p_bird_swan=&swan as &dyn Bird;
	let p_bird_duck=p_duck as &dyn Bird;
	let Duck_fly:usize=Duck::fly as usize;
	let Swan_fly:usize=Swan::fly as usize;
	// let addr_duck=&duck as usize;
	// let addr_swan=&swan as usize;
	println!("data addr:{:p} {:p}",&duck,&swan);
	println!("func addr:{} {}",Duck_fly,Swan_fly);
	print_object(p_bird_duck);
	print_object(p_bird_swan);
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值