#![cfg(windows)] extern crate lpwstr; extern crate winapi; use std::ffi::OsString; use std::mem; use std::ptr; use lpwstr::FromWide; use winapi::shared::winerror::ERROR_BUFFER_OVERFLOW; use winapi::um::errhandlingapi::GetLastError; use winapi::um::winbase::GetComputerNameW; fn main() { let computer_name; unsafe { // Find the needed size let mut chars_needed = 0; assert_eq!(GetComputerNameW(ptr::null_mut(), &mut chars_needed), 0); assert_eq!(GetLastError(), ERROR_BUFFER_OVERFLOW); // Allocate and get the name let mut buffer = vec![mem::uninitialized(); chars_needed as usize]; assert_ne!(GetComputerNameW(buffer.as_mut_ptr(), &mut chars_needed), 0); // chars_needed is now the character count not including the null terminator assert_eq!(buffer[buffer.len()-1], 0); computer_name = OsString::from_wide_ptr_null(buffer.as_ptr()); assert_eq!(computer_name.len(), chars_needed as usize); } println!("{}", computer_name.to_string_lossy()); }