From 58db8968138858a3f53d8836109c18cdee5b8723 Mon Sep 17 00:00:00 2001 From: Sebastian Wiesner Date: Thu, 27 Oct 2022 10:00:44 +0200 Subject: [PATCH] Use windows-rs instead of winapi --- Cargo.toml | 5 ++++- src/lib.rs | 28 +++++++++++++--------------- 2 files changed, 17 insertions(+), 16 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 5a587ca..85a19e4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,4 +16,7 @@ categories = ["os", "api-bindings"] libc = "^0.2" [target.'cfg(windows)'.dependencies] -winapi = { version = "^0.3", features = ["sysinfoapi"] } +windows = { version = "0.43.0", features = [ + "Win32_System_SystemInformation", + "Win32_Foundation", +] } diff --git a/src/lib.rs b/src/lib.rs index f324f28..253af4a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -90,36 +90,34 @@ fn gethostname_impl() -> OsString { #[inline] fn gethostname_impl() -> OsString { use std::os::windows::ffi::OsStringExt; - use winapi::ctypes::{c_ulong, wchar_t}; - use winapi::um::sysinfoapi::{ComputerNamePhysicalDnsHostname, GetComputerNameExW}; + use windows::core::PWSTR; + use windows::Win32::System::SystemInformation::{ + ComputerNamePhysicalDnsHostname, GetComputerNameExW, + }; - let mut buffer_size: c_ulong = 0; + let mut buffer_size: u32 = 0; unsafe { // This call always fails with ERROR_MORE_DATA, because we pass NULL to // get the required buffer size. GetComputerNameExW( ComputerNamePhysicalDnsHostname, - std::ptr::null_mut(), + PWSTR::null(), &mut buffer_size, ) }; - let mut buffer = vec![0 as wchar_t; buffer_size as usize]; - let returncode = unsafe { + let mut buffer = vec![0 as u16; buffer_size as usize]; + unsafe { GetComputerNameExW( ComputerNamePhysicalDnsHostname, - buffer.as_mut_ptr() as *mut wchar_t, + PWSTR::from_raw(buffer.as_mut_ptr()), &mut buffer_size, ) - }; - // GetComputerNameExW returns a non-zero value on success! - if returncode == 0 { - panic!( - "GetComputerNameExW failed to read hostname: {} -Please report this issue to !", - Error::last_os_error() - ); + .expect( + "GetComputerNameExW failed to read hostname. + Please report this issue to !", + ) } let end = buffer.iter().position(|&b| b == 0).unwrap_or(buffer.len());