Skip to content

Add ComPtr::new_class #22

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ targets = [
[dependencies]
log = { version = "0.4", optional = true }
winapi = { version = "0.3", features = [
"combaseapi",
"consoleapi",
"errhandlingapi",
"fileapi",
Expand Down
43 changes: 40 additions & 3 deletions src/com.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,17 @@ use std::fmt::{Debug, Error as FmtError, Formatter};
use std::mem::forget;
use std::ops::Deref;
use std::ptr::{null_mut, NonNull};
use winapi::um::unknwnbase::IUnknown;
use winapi::Interface;
use winapi::{
shared::{
minwindef::DWORD,
winerror::HRESULT,
},
um::{
combaseapi,
unknwnbase::IUnknown,
}
};
use winapi::{Class, Interface};

// ComPtr to wrap COM interfaces sanely
#[repr(transparent)]
Expand Down Expand Up @@ -57,6 +66,34 @@ impl<T> ComPtr<T> {
}
}
}
/// Instantiate the given class type.
///
/// This is a shorthand for [`CoCreateInstance`], using `C` and `T`'s `GUID`s for `rclsid` and
/// `riid`, respectively. `cls_context` is passed into [`CoCreateInstance`]'s `dwClsContext`
/// parameter, so see that documentation for details on what to pass for it.
///
/// Returns `Err(HRESULT)` if the call to [`CoCreateInstance`] failed.
///
/// [`CoCreateInstance`]: https://docs.microsoft.com/en-us/windows/win32/api/combaseapi/nf-combaseapi-cocreateinstance
pub fn new_class<C: Class>(cls_context: DWORD) -> Result<ComPtr<T>, HRESULT>
where T: Interface
{
unsafe {
let mut raw_ptr: *mut T = null_mut();
let hr = combaseapi::CoCreateInstance(
&C::uuidof(),
null_mut(),
cls_context,
&T::uuidof(),
&mut raw_ptr as *mut _ as *mut _,
);
if hr == 0 {
Ok(ComPtr::from_raw(raw_ptr))
} else {
Err(hr)
}
}
}
/// Casts up the inheritance chain
pub fn up<U>(self) -> ComPtr<U>
where
Expand All @@ -77,7 +114,7 @@ impl<T> ComPtr<T> {
unsafe { &*(self.as_raw() as *mut IUnknown) }
}
/// Performs QueryInterface fun.
pub fn cast<U>(&self) -> Result<ComPtr<U>, i32>
pub fn cast<U>(&self) -> Result<ComPtr<U>, HRESULT>
where
U: Interface,
{
Expand Down