You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Rust中通过Windows COM调用bPac SDK实现标签打印

Rust 对接 bPac SDK 最简打印示例

前置依赖配置

在Cargo.toml中添加windows依赖,开启所需功能项:

[dependencies.windows]
version = "0.51.1"
features = [
    "Win32_System_Com",
    "Win32_Foundation",
]

可运行代码

不需要手动处理IDispatch的GetIDsOfNames、Invoke等底层调用逻辑,也不需要引入兼容性存疑的第三方crate,直接用windows crate提供的COM接口宏声明bPac的文档接口即可,逻辑完全对应提供的Ruby示例:

use windows::{
    core::BSTR,
    Win32::System::Com::{
        CoCreateInstance, CoInitializeEx, CLSCTX_ALL, COINIT_APARTMENTTHREADED, IDispatch,
    },
};

// bPac Document接口绑定,IID为本机安装bPac SDK后注册表中存储的固定值
#[windows::interface("5F9B7B9B-9F26-4F5B-A00D-0F2A8C2A7D2C")]
unsafe trait IBpacDocument: IDispatch {
    fn Open(&self, label_path: &BSTR) -> windows::core::BOOL;
    fn SetPrinter(&self, printer_name: &BSTR, set_default: windows::core::BOOL) -> windows::core::BOOL;
    fn StartPrint(&self, job_name: &BSTR, options: i32) -> windows::core::BOOL;
    fn PrintOut(&self, copy_count: i32, options: i32) -> windows::core::BOOL;
    fn EndPrint(&self) -> windows::core::BOOL;
}

pub fn print_label() -> windows::core::Result<()> {
    unsafe {
        // 初始化STA线程COM环境
        CoInitializeEx(None, COINIT_APARTMENTTHREADED)?;

        // 创建bpac.Document COM实例,直接转换为自定义的强类型接口
        let doc: IBpacDocument = CoCreateInstance(
            &windows::core::CLSID::from_progid("bpac.Document")?,
            None,
            CLSCTX_ALL,
        )?;

        // 调用逻辑与Ruby示例完全一致
        doc.Open(&BSTR::from("some_label.lbx"));
        doc.SetPrinter(&BSTR::from("Brother QL-810W"), true);

        const PRINT_OPTS: i32 = 0;
        doc.StartPrint(&BSTR::from(""), PRINT_OPTS);
        doc.PrintOut(1, PRINT_OPTS);
        doc.EndPrint();
    }
    Ok(())
}

注意事项

  • 如果运行时提示接口不匹配,可在本机注册表搜索bpac.Document项,找到对应类型库下的Interface IID,替换代码中#[windows::interface(...)]里的GUID值即可。
  • 注意bPac SDK的位数要和Rust编译目标平台一致:官方默认安装的是32位版本SDK,如果编译64位程序会找不到COM对象,可选择安装64位版bPac SDK,或者将编译目标设置为i686-pc-windows-msvc。
  • BSTR是COM要求的字符串类型,由windows crate自动管理内存,不需要手动释放。

内容的提问来源于stack exchange,提问作者Rogier

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 16:42:58