diff --git a/crates/libs/core/src/handles.rs b/crates/libs/core/src/handles.rs index b35c29e6cc..14cf29ee76 100644 --- a/crates/libs/core/src/handles.rs +++ b/crates/libs/core/src/handles.rs @@ -19,7 +19,8 @@ impl Owned { /// Takes ownership of the handle. /// /// # Safety - /// The handle must be owned by the caller and safe to free. + /// + /// The handle must be owned by the caller and safe to free. pub unsafe fn new(x: T) -> Self { Self(x) } diff --git a/crates/libs/registry/src/key.rs b/crates/libs/registry/src/key.rs index 9d41b83ca8..2701288846 100644 --- a/crates/libs/registry/src/key.rs +++ b/crates/libs/registry/src/key.rs @@ -37,6 +37,16 @@ impl Key { win32_error(result).map(|_| Self(handle)) } + /// Constructs a registry key from an existing handle. + /// + /// # Safety + /// + /// This function takes ownership of the handle. + /// The handle must be owned by the caller and safe to free with `RegCloseKey`. + pub unsafe fn from_raw(handle: isize) -> Self { + Self(handle) + } + /// Returns the underlying registry key handle. pub fn as_raw(&self) -> isize { self.0 diff --git a/crates/tests/registry/tests/sys_interop.rs b/crates/tests/registry/tests/sys_interop.rs index 0b9107ed46..52c10b1ae9 100644 --- a/crates/tests/registry/tests/sys_interop.rs +++ b/crates/tests/registry/tests/sys_interop.rs @@ -11,11 +11,15 @@ fn sys_interop() -> Result<()> { key.set_u32("2", 2)?; key.set_u32("3", 3)?; + let raw: HKEY = key.as_raw(); + std::mem::forget(key); + let owned = unsafe { Key::from_raw(raw) }; + let mut count = 0; unsafe { RegQueryInfoKeyW( - key.as_raw(), + owned.as_raw(), std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut(), diff --git a/crates/tests/registry/tests/windows_interop.rs b/crates/tests/registry/tests/windows_interop.rs index 6446773109..2d0e3628ea 100644 --- a/crates/tests/registry/tests/windows_interop.rs +++ b/crates/tests/registry/tests/windows_interop.rs @@ -11,11 +11,15 @@ fn windows_interop() -> Result<()> { key.set_u32("2", 2)?; key.set_u32("3", 3)?; + let raw = HKEY(key.as_raw()); + std::mem::forget(key); + let owned = unsafe { Key::from_raw(raw.0) }; + let mut count = 0; unsafe { RegQueryInfoKeyW( - HKEY(key.as_raw()), + HKEY(owned.as_raw()), PWSTR::null(), None, None,