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)
}
vin your code, or is it opaque? If it's opaque, all of this is not necessary.UnsafeCell? or*mut c_void(which I think would be necessory...)UnsafeCellinforms the Rust compiler that a value may change at any time, even though the compiler can see a shared reference to it. This is important for when the compiler wants to use the value, so that it knows it can't just hold it in a register. But if the compiler never touches the field, because it's only touched by FFI functions, then the annotation isn't necessary.UnsafeCelldoes not requireSized, so we can put DST in it...