pub struct ComPtr<T: ComInterface> { /* private fields */ }Expand description
Wrapper type for COM interface pointers.
§Usage
§Passing COM pointers to/from FFI methods
ComPtr<T> has the following methods for accessing the underlying pointer:
as_ptrreturns the raw pointer*const Tas_mut_ptrreturns a mutable reference to the raw pointer&mut *mut T
The AsComPtr trait defines which pointer types can be returned by these
methods. These methods should be used carefully to ensure the returned pointers
do not outlive the ComPtr object.
extern crate com_rs;
use com_rs::*;
fn create_iunknown_object(p: *mut *mut IUnknown) { }
fn use_iunknown_object(p: *const IUnknown) { }
fn main() {
let mut unknown: ComPtr<IUnknown> = ComPtr::new();
create_iunknown_object(unknown.as_mut_ptr());
use_iunknown_object(unknown.as_ptr());
}§Reference Counting
ComPtr implements the Clone and Drop traits, which call the
IUnknown::add_ref and IUnknown::release methods respectively to handle the
internal reference counting.
§Accessing COM interface methods
ComPtr<T> coerces into T using the Deref trait, allowing interface methods
to be called directly. However, dereferencing a ComPtr containing a null
pointer in this way results in a panic. All method calls should be guarded with
is_null checks to prevent this.
let mut ptr: ComPtr<IUnknown> = ComPtr::new();
create_iunknown_object(ptr.as_mut_ptr());
if !ptr.is_null() {
// This is just for demonstration, don't call these directly
unsafe { ptr.add_ref() };
unsafe { ptr.release() };
}§Conversion using From
ComPtr<T> also implements the From trait for conversion between different
COM interfaces. This is a wrapper around the IUnknown::query_interface method
which automatically uses the IID of the target type.
let mut unknown: ComPtr<IUnknown> = ComPtr::new();
create_iunknown_object(unknown.as_mut_ptr());
let other: ComPtr<IFoobar> = ComPtr::from(&unknown);This will try to query the IFoobar interface on the unknown object. If the
interface is unavailable (or unknown is null), the returned object will be
null.
Implementations§
Source§impl<T: ComInterface> ComPtr<T>
impl<T: ComInterface> ComPtr<T>
Sourcepub fn as_ptr<U>(&self) -> *const Uwhere
T: AsComPtr<U>,
pub fn as_ptr<U>(&self) -> *const Uwhere
T: AsComPtr<U>,
Returns the raw pointer as type U. Depends on the AsComPtr trait.
Sourcepub fn as_mut_ptr<U>(&mut self) -> &mut *mut Uwhere
T: AsComPtr<U>,
pub fn as_mut_ptr<U>(&mut self) -> &mut *mut Uwhere
T: AsComPtr<U>,
Returns a mutable reference to the raw pointer. Depends on the ‘AsComPtr’ trait.