rust raw pointer使用方法(1)

1、raw pointer的声明与赋值
这个是c_void类型的用法,可以看到c_void类型的变量是没法赋值的,估计是故意被设计成这样防止滥用,只有*const c_void和*mut c_void才赋值

use std::os::raw::{c_void};

const NULL:* mut c_void = 0 as *mut c_void;

fn main() {
    //*mut
    let mut c:*mut c_void=1 as * mut c_void;
    println!("c:{},{:?}",std::mem::size_of_val(&c),c);

    c = 2 as *mut c_void;
    println!("c:{},{:?}",std::mem::size_of_val(&c),c);

    c = NULL;
    println!("c:{},{:?}",std::mem::size_of_val(&c),c);

    //ok
    let mut d:c_void;
    //fail
    //d = 5 as c_void;

    //*const
    let mut e: *const c_void = 3 as *const c_void;
    println!("e:{},{:?}",std::mem::size_of_val(&e),e);

    e = 4 as *const c_void;
    println!("e:{},{:?}",std::mem::size_of_val(&e),e);

    e = NULL;
    println!("e:{},{:?}",std::mem::size_of_val(&e),e);
}

注意这个:let mut e:*const c_void,e之所以能改变是因为e是mut的,但是e指向的内容 *e是不可以改变的,这个与c++的const指针有类似的地方,这个要注意分清楚

在Play上能正确运行的:http://is.gd/svFNU6
运行结果

c:8,0x1
c:8,0x2
c:8,0x0
e:8,0x3
e:8,0x4
e:8,0x0

你可能感兴趣的:(Rust,rawpointer,c-void)