1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
use std::{mem, ptr};
use windows::Win32::{Foundation::PWSTR, Globalization::lstrlenW, System::Com};
pub fn string_from_pwstr(source: &PWSTR) -> String {
if source.0.is_null() {
String::new()
} else {
let len = unsafe { lstrlenW(source) };
if len > 0 {
unsafe {
let buffer = ptr::slice_from_raw_parts(source.0, len as usize);
String::from_utf16_lossy(&*buffer)
}
} else {
String::new()
}
}
}
pub fn take_pwstr(source: PWSTR) -> String {
let result = string_from_pwstr(&source);
if !source.0.is_null() {
unsafe {
Com::CoTaskMemFree(mem::transmute(source.0));
}
}
result
}
pub fn pwstr_from_str(source: &str) -> PWSTR {
match source {
"" => PWSTR(ptr::null_mut::<u16>()),
value => {
let encoded: Vec<_> = value.encode_utf16().chain(std::iter::once(0)).collect();
unsafe {
let mut buffer =
Com::CoTaskMemAlloc(encoded.len() * mem::size_of::<u16>()) as *mut u16;
let result = PWSTR(buffer);
for char in encoded {
*buffer = char;
buffer = buffer.add(1);
}
result
}
}
}
}