'How to get a mutable u32 pointer and cast it into an int pointer of C

Let's say I have a C function:

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

To call it in Rust, I declared:

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

Then I wrote another wrapper:

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!()
}

But the compiler told me:

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

Why can't I cast capacity into *mut c_unit?



Solution 1:[1]

It turns out I have to make the reference mutable.

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1