如何获取可变的u32指针并将其转换为C

时间:2018-10-15 07:35:02

标签: rust ffi

假设我有一个C函数:

void func(char *buf, unsigned int *len);

要在Rust中调用它,我声明:

pub fn func(buf: *mut ::std::os::raw::c_char, len: *mut ::std::os::raw::c_uint) {
    unimplemented!()
}

然后我写了另一个包装器:

pub fn another_func() -> String {
    let mut capacity: u32 = 256;
    let mut vec = Vec::with_capacity(capacity as usize);
    unsafe {
        func(vec.as_ptr() as *mut c_char, &capacity as *mut c_uint)
    };
    String::from_utf8(vec).unwrap();
    unimplemented!()
}

但是编译器告诉我:

error[E0606]: casting `&u32` as `*mut u32` is invalid
   --> src/main.rs:...:28
    |
307 |                                  &capacithy as *mut c_uint)

为什么不能将capacity投射到*mut c_unit中?

1 个答案:

答案 0 :(得分:0)

最后我找到了anwser,我必须给它一个易变的迹象:

func(vec.as_ptr() as *mut c_char, &mut capacity as *mut c_uint)