Reputation: 3076
I am writing a C-interfacing library in rust. My API is very C-like: I get "opaque" pointers as a function argument that I must cast into a pointer to my library-internal struct. So the lifetime of the pointer is longer than the function call (static) and the pointer points to mutable data (the library is responsible for initializing and getting/setting this data). Mutability + static data is implicitly part of the API, but in rust I am having trouble (I think with just syntax) stating this.
The code looks like this:
struct Real_attr { ... }
pub extern "C" fn attr_init(attr: *mut attr_ptr) -> cty::c_int {
let p : *mut Real_attr = attr.cast::<Real_attr>();
let r : &mut Real_attr = p.as_ref::<'static'>().unwrap();
...
}
Which gives me a error:
42 | p.as_ref::<'static>()
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ types differ in mutability
|
= note: expected enum `Option<&'static mut Real_attr>`
found enum `Option<&'static Real_attr>`
But I don't understand how to "cast" or otherwise specify that reference to be mutable, adding in the mut
after static gets me syntax errors..
Upvotes: 1
Views: 1474
Reputation: 70377
If you want a mutable reference, you're looking for as_mut
.
let r : &mut Real_attr = p.as_mut::<'static>().unwrap();
Upvotes: 2