rust
let v: i32 = 10;
let v1 = &v;
let a: *const i32 = &v;
println!("a={:p}", a);
let b = a as *mut i32; //无法从&v直接转换成*mut i32,需要从*const i32过度
println!("b={:p}", b);
unsafe {
*b+=1;
}
println!("v={} v1={}", v, v1);
输出
a=0xa7c8fb4d8 b=0xa7c8fb4d8 v=11 v1=11
rust
let mut mv: i32 = 10;
let mut mv2 = &mut mv;
*mv2 = *mv2 + 1;
let p1 = mv2 as *const i32 as *mut i32;
unsafe {
*p1 += 1;
}
//let p2 = mv2 as *const i32;
let mv3 = unsafe {
let i: i32 = *p1;
i
};
println!("mv2={} mv3={}", mv2, mv3);
mv2=12 mv3=12
rust
use std::borrow::Cow;
use std::os::raw::c_char;
use std::ffi::CStr;
let C: [u8; 11] = [116, 104, 97, 110, 107, 115, 102, 105, 115, 104, 0];
let c_str: Cow<str>;
unsafe{
let c_ptr = &C as *const u8 as *const c_char;
c_str = CStr::from_ptr(c_ptr).to_string_lossy();
}
println!("c_str is {}", c_str);
c_str is thanksfish
原始指针和unsafe块配合,可以避过引用借用保护,但也失去了rust的优势。rust严谨也足够灵活...,除非必要原始指针慎用,用多了又变成c了...