Skip to content

Commit

Permalink
Use windows-rs instead of winapi
Browse files Browse the repository at this point in the history
  • Loading branch information
swsnr committed Oct 27, 2022
1 parent 8550576 commit 58db896
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 16 deletions.
5 changes: 4 additions & 1 deletion Cargo.toml
Expand Up @@ -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",
] }
28 changes: 13 additions & 15 deletions src/lib.rs
Expand Up @@ -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 <https://github.com/lunaryorn/gethostname.rs/issues>!",
Error::last_os_error()
);
.expect(
"GetComputerNameExW failed to read hostname.
Please report this issue to <https://github.com/lunaryorn/gethostname.rs/issues>!",
)
}

let end = buffer.iter().position(|&b| b == 0).unwrap_or(buffer.len());
Expand Down

0 comments on commit 58db896

Please sign in to comment.