cxx icon indicating copy to clipboard operation
cxx copied to clipboard

Add UniquePtr::as_mut_ptr

Open adetaylor opened this issue 3 years ago • 3 comments

cxx accepts functions that take *mut T as an argument. Such functions are of course used under odd niche circumstances; it would be safer and better to take a &mut Pin<T>.

But in cases where such a function does exist, we'd most commonly want to provide it a mutable pointer to a T which is safely and uniquely owned by Rust, within a UniquePtr.

It was previously quite hard to do this:

    let mut a = /* make UniquePtr to a thing */
    unsafe { ffi::TakeA(std::pin::Pin::<&mut ffi::A>::into_inner_unchecked(a.pin_mut())) };

With this extra API, it becomes much more ergonomic:

    let mut a = /* make UniquePtr to a thing */
    unsafe { ffi::TakeA(a.as_mut_ptr()) }

Inspired by https://github.com/google/autocxx/issues/558

adetaylor avatar Jun 25 '21 23:06 adetaylor

Thanks. I wasn't quite sure. On the one hand, manipulating the returned pointer could break the contents of the UniquePtr (so it's unsafe in that sense) but on the other hand, such unsafety is restricted to the contents of the UniquePtr and that's wild-west C++ land anyway.

I'll revise the PR to remove the unsafe. Thanks.

adetaylor avatar Jun 29 '21 14:06 adetaylor

You can also remove the exclusive reference to self and use a shared reference. Getting the pointer from a unique_ptr doesn't require that the caller has exclusive access to the unique_ptr.

dtolnay avatar Jun 29 '21 18:06 dtolnay

Hey, any updates to this to make it merge?

theomonnom avatar Sep 18 '22 13:09 theomonnom