首页 > 解决方案 > 如何获取可变 u32 指针并将其转换为 C 的 int 指针

问题描述

假设我有一个 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 |                                  &capacity as *mut c_uint)

为什么我不能投capacity进去*mut c_unit

标签: rustffi

解决方案


我必须使引用可变。

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

推荐阅读