diff --git a/src/unique_ptr.rs b/src/unique_ptr.rs index 1a657cbab..5f8019586 100644 --- a/src/unique_ptr.rs +++ b/src/unique_ptr.rs @@ -90,6 +90,26 @@ where } } + /// Returns a pointer to the object owned by this UniquePtr + /// if any, otherwise the null pointer. + pub fn as_ptr(&self) -> *const T { + match self.as_ref() { + Some(target) => target as *const T, + None => std::ptr::null(), + } + } + + /// Returns a mutable pointer to the object owned by this UniquePtr + /// if any, otherwise the null pointer. + /// + /// As with [std::unique_ptr\::get](https://en.cppreference.com/w/cpp/memory/unique_ptr/get), + /// this doesn't require that you hold a mutable reference to the `UniquePtr`. + /// This differs from Rust norms, so extra care should be taken in + /// the way the pointer is used. + pub fn as_mut_ptr(&self) -> *mut T { + self.as_ptr() as *mut T + } + /// Consumes the UniquePtr, releasing its ownership of the heap-allocated T. /// /// Matches the behavior of [std::unique_ptr\::release](https://en.cppreference.com/w/cpp/memory/unique_ptr/release). diff --git a/tests/test.rs b/tests/test.rs index ac396589c..6d9ba34c1 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -259,6 +259,8 @@ fn test_c_method_calls() { assert_eq!(2021, unique_ptr.get()); assert_eq!(2021, unique_ptr.get2()); assert_eq!(2021, *unique_ptr.getRef()); + assert_eq!(2021, unsafe { unique_ptr.as_mut_ptr().as_ref() }.unwrap().get()); + assert_eq!(2021, unsafe { unique_ptr.as_ptr().as_ref() }.unwrap().get()); assert_eq!(2021, *unique_ptr.pin_mut().getMut()); assert_eq!(2022, unique_ptr.pin_mut().set_succeed(2022).unwrap()); assert!(unique_ptr.pin_mut().get_fail().is_err());