#com #com-interface #winapi #reference-counting #windows

derive-com-impl

帮助从Rust实现COM接口的过程宏

6个版本

0.2.0 2023年7月25日
0.1.1 2019年3月1日
0.1.0 2019年3月1日
0.1.0-alpha32018年11月11日

#com-interface中排名第18

Download history 29/week @ 2024-03-11 30/week @ 2024-03-18 24/week @ 2024-03-25 51/week @ 2024-04-01 19/week @ 2024-04-08 24/week @ 2024-04-15 30/week @ 2024-04-22 28/week @ 2024-04-29 28/week @ 2024-05-06 36/week @ 2024-05-13 50/week @ 2024-05-20 36/week @ 2024-05-27 39/week @ 2024-06-03 31/week @ 2024-06-10 23/week @ 2024-06-17 42/week @ 2024-06-24

每月下载量138
4个crate中使用(其中2个直接使用)

MIT协议

37KB
826

实现具有自动引用计数的COM对象结构体,并为您实现IUnknown。这涵盖了从Rust创建COM对象的最常见用例。支持泛型参数!

#[macro_use]
extern crate derive_com_impl;

extern crate com_impl;
extern crate winapi;
extern crate wio;

use com_impl::{VTable, Refcount};
use winapi::ctypes::c_void;
use winapi::shared::winerror::{ERROR_INVALID_INDEX, HRESULT, HRESULT_FROM_WIN32, S_OK};
use winapi::um::dwrite::{IDWriteFontFileStream, IDWriteFontFileStreamVtbl};
use wio::com::ComPtr;

#[repr(C)]
#[derive(ComImpl)]
#[interfaces(IDWriteFontFileStream)]
pub struct FileStream {
    vtbl: VTable<IDWriteFontFileStreamVtbl>,
    refcount: Refcount,
    write_time: u64,
    file_data: Vec<u8>,
}

impl FileStream {
    pub fn new(write_time: u64, data: Vec<u8>) -> ComPtr<IDWriteFontFileStream> {
        let ptr = FileStream::create_raw(write_time, data);
        let ptr = ptr as *mut IDWriteFontFileStream;
        unsafe { ComPtr::from_raw(ptr) }
    }
}

#[com_impl]
unsafe impl IDWriteFontFileStream for FileStream {
    unsafe fn get_file_size(&self, size: *mut u64) -> HRESULT {
        *size = self.file_data.len() as u64;
        S_OK
    }

    unsafe fn get_last_write_time(&self, write_time: *mut u64) -> HRESULT {
        *write_time = self.write_time;
        S_OK
    }

    unsafe fn read_file_fragment(
        &self,
        start: *mut *const c_void,
        offset: u64,
        size: u64,
        ctx: *mut *mut c_void,
    ) -> HRESULT {
        if offset > std::isize::MAX as u64 || size > std::isize::MAX as u64 {
            return HRESULT_FROM_WIN32(ERROR_INVALID_INDEX);
        }

        let offset = offset as usize;
        let size = size as usize;

        if offset + size > self.file_data.len() {
            return HRESULT_FROM_WIN32(ERROR_INVALID_INDEX);
        }

        *start = self.file_data.as_ptr().offset(offset as isize) as *const c_void;
        *ctx = std::ptr::null_mut();

        S_OK
    }

    unsafe fn release_file_fragment(&self, _ctx: *mut c_void) {
        // Nothing to do
    }
}

fn main() {
    let ptr = FileStream::new(100, vec![0xDE, 0xAF, 0x00, 0xF0, 0x01]);

    // Do things with ptr
}

依赖项

~2MB
~46K SLoC