The UnsafeCell
documentation says
The
UnsafeCell<T>
type is the only legal way to obtain aliasable data that is considered mutable.
The only construction method is:
pub const fn new(value: T) -> UnsafeCell<T>
However, it is not possible to create a c_void
, we can only create *mut c_void
or *const c_void
.
Is it possible to create UnsafeCell<c_void>
from a *mut c_void
? With this, we can let the compiler know that the pointer can point to something mutable.
Or is this not necessary? Can we always use *mut c_void
even we know some FFI call will mutate the data it points to and we have multiple references to it?
A use case would be:
struct FFIStruct { v: UnsafeCell<c_void>, other_fields: ... }
impl FFIStruct {
// We don't want to require &mut self, as we
// are sure private call_ffi() will always be called
// sequentially, and we don't want to stop
// status() being callable during the call
fn call_ffi(&self){ ffi_function(self.v.get()) }
pub fn status(&self) -> FFIStatus { ... }
}
Now how do we create FFIStruct
? Or just use *mut c_void
would be OK?
Example code to create &Cell<c_void>
Requires #![feature(as_cell)]
:
unsafe fn get_cell<'a>(p: *mut c_void) -> &'a Cell<c_void> {
Cell::from_mut(&mut *p)
}