unsafefnmodify_by_address(address:usize){// TODO: Fill your safety notice of the code block below to match your// code's behavior and the contract of this function. You may use the// comment of the test below as your format reference.unsafe{//todo!("Your code goes here")let ptr = address as*mutu32;*ptr =0xAABBCCDD;}}#[cfg(test)]modtests{usesuper::*;#[test]fntest_success(){letmut t:u32=0x12345678;// SAFETY: The address is guaranteed to be valid and contains// a unique reference to a `u32` local variable.unsafe{modify_by_address(&mut t as*mutu32asusize)};assert!(t ==0xAABBCCDD);}}
当对一个引用转换为*mut u32时,这时候的值就是地址了。
对地址解引用就可以直接操作内存。
将指针转换为Box
unsafefnraw_pointer_to_box(ptr:*mutFoo)->Box<Foo>{// SAFETY: The `ptr` contains an owned box of `Foo` by contract. We// simply reconstruct the box from that pointer.letmut ret:Box<Foo>=unsafe{letmut ret =Box::from_raw(ptr);ret.b =Some("hello".to_owned());ret};//todo!("The rest of the code goes here")ret
}
实现了由不安全到安全的转变
链接 ,全局符号
extern"Rust"{fnmy_demo_function(a:u32)->u32;#[link_name = "my_demo_function"]fnmy_demo_function_alias(a:u32)->u32;}modFoo{// No `extern` equals `extern "Rust"`.#[no_mangle]fnmy_demo_function(a:u32)->u32{a}}#[cfg(test)]modtests{usesuper::*;#[test]fntest_success(){// The externally imported functions are UNSAFE by default// because of untrusted source of other languages. You may// wrap them in safe Rust APIs to ease the burden of callers.//// SAFETY: We know those functions are aliases of a safe// Rust function.unsafe{my_demo_function(123);my_demo_function_alias(456);}}}