Debian Codegraph @

third_party/rust/cc/src/windows/com.rs

raw
1 // Copyright © 2017 winapi-rs developers
2 // Licensed under the Apache License, Version 2.0
3 // <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
4 // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
5 // All files in the project carrying such notice may not be copied, modified, or distributed
6 // except according to those terms.
7
8 use crate::windows::{
9 winapi::{IUnknown, Interface},
10 windows_sys::{
11 CoInitializeEx, SysFreeString, SysStringLen, BSTR, COINIT_MULTITHREADED, HRESULT, S_FALSE,
12 S_OK,
13 },
14 };
15 use std::{
16 convert::TryInto,
17 ffi::OsString,
18 ops::Deref,
19 os::windows::ffi::OsStringExt,
20 ptr::{null, null_mut},
21 slice::from_raw_parts,
22 };
23
24 pub fn initialize() -> Result<(), HRESULT> {
25 let err = unsafe { CoInitializeEx(null(), COINIT_MULTITHREADED.try_into().unwrap()) };
26 if err != S_OK && err != S_FALSE {
27 // S_FALSE just means COM is already initialized
28 Err(err)
29 } else {
30 Ok(())
31 }
32 }
33
34 pub struct ComPtr<T>(*mut T)
35 where
36 T: Interface;
37 impl<T> ComPtr<T>
38 where
39 T: Interface,
40 {
41 /// Creates a `ComPtr` to wrap a raw pointer.
42 /// It takes ownership over the pointer which means it does __not__ call `AddRef`.
43 /// `T` __must__ be a COM interface that inherits from `IUnknown`.
44 pub unsafe fn from_raw(ptr: *mut T) -> ComPtr<T> {
45 assert!(!ptr.is_null());
46 ComPtr(ptr)
47 }
48 /// For internal use only.
49 fn as_unknown(&self) -> &IUnknown {
50 unsafe { &*(self.0 as *mut IUnknown) }
51 }
52 /// Performs `QueryInterface` fun.
53 pub fn cast<U>(&self) -> Result<ComPtr<U>, i32>
54 where
55 U: Interface,
56 {
57 let mut obj = null_mut();
58 let err = unsafe { self.as_unknown().QueryInterface(&U::uuidof(), &mut obj) };
59 if err < 0 {
60 return Err(err);
61 }
62 Ok(unsafe { ComPtr::from_raw(obj as *mut U) })
63 }
64 }
65 impl<T> Deref for ComPtr<T>
66 where
67 T: Interface,
68 {
69 type Target = T;
70 fn deref(&self) -> &T {
71 unsafe { &*self.0 }
72 }
73 }
74 impl<T> Clone for ComPtr<T>
75 where
76 T: Interface,
77 {
78 fn clone(&self) -> Self {
79 unsafe {
80 self.as_unknown().AddRef();
81 ComPtr::from_raw(self.0)
82 }
83 }
84 }
85 impl<T> Drop for ComPtr<T>
86 where
87 T: Interface,
88 {
89 fn drop(&mut self) {
90 unsafe {
91 self.as_unknown().Release();
92 }
93 }
94 }
95 pub struct BStr(BSTR);
96 impl BStr {
97 pub unsafe fn from_raw(s: BSTR) -> BStr {
98 BStr(s)
99 }
100 pub fn to_osstring(&self) -> OsString {
101 let len = unsafe { SysStringLen(self.0) };
102 let slice = unsafe { from_raw_parts(self.0, len as usize) };
103 OsStringExt::from_wide(slice)
104 }
105 }
106 impl Drop for BStr {
107 fn drop(&mut self) {
108 unsafe { SysFreeString(self.0) };
109 }
110 }