windows C++-WRL 创建传统型 COM 组件

2024-08-26 05:44

本文主要是介绍windows C++-WRL 创建传统型 COM 组件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

除了用于通用 Windows 平台 (UWP) 应用程序,还可以使用 Windows 运行时 C++ 模板库 (WRL) 创建用于桌面应用程序的基本传统型 COM 组件。 用于创建 COM 组件时,Windows 运行时 C++ 模板库需要的代码可能比 ATL 少。 

本文演示如何使用 Windows 运行时 C++ 模板库创建基本 COM 组件。 尽管可以使用最适合你需求的部署机制,本文还会展示一种从桌面应用程序注册及使用 COM 组件的基本方法。

使用 Windows 运行时 C++ 模板库创建基本传统型 COM 组件
  1. 在 Visual Studio 中,创建一个“空白解决方案”项目。 为该项目命名,例如 WRLClassicCOM。
  2. 向该解决方案添加“Win32 项目”。 为该项目命名,例如 CalculatorComponent。 在“应用程序设置”选项卡上,选择“DLL”。
  3. 向该项目添加“Midl 文件(.idl)”文件。 为该文件命名,例如,CalculatorComponent.idl。
  4. 将此代码添加到 CalculatorComponent.idl:
    import "ocidl.idl";[uuid(0DBABB94-CE99-42F7-ACBD-E698B2332C60), version(1.0)] 
    interface ICalculatorComponent : IUnknown
    {HRESULT Add([in] int a, [in] int b, [out, retval] int* value);
    }[uuid(9D3E6826-CB8E-4D86-8B14-89F0D7EFCD01), version(1.0)]
    library CalculatorComponentLib
    {[uuid(E68F5EDD-6257-4E72-A10B-4067ED8E85F2), version(1.0)]coclass CalculatorComponent{[default] interface ICalculatorComponent;}
    };
  5. 在 CalculatorComponent.cpp 中,定义 CalculatorComponent 类。 CalculatorComponent 类继承自 Microsoft::WRL::RuntimeClass。 Microsoft::WRL::RuntimeClassFlags<ClassicCom> 指定类派生自 IUnknown 而不是 IInspectable。 IInspectable 仅适用于 Windows 运行时应用程序组件。CoCreatableClass 为可与 CoCreateInstance 等函数一起使用的类创建一个工厂。
    #include "pch.h" // Use stdafx.h in Visual Studio 2017 and earlier#include "CalculatorComponent_h.h"
    #include <wrl.h>using namespace Microsoft::WRL;class CalculatorComponent: public RuntimeClass<RuntimeClassFlags<ClassicCom>, ICalculatorComponent>
    {
    public:CalculatorComponent(){}STDMETHODIMP Add(_In_ int a, _In_ int b, _Out_ int* value){*value = a + b;return S_OK;}
    };CoCreatableClass(CalculatorComponent);
  6. 用下面的代码替换 dllmain.cpp 中的代码。 此文件定义 DLL 导出函数。 这些函数使用 Microsoft::WRL::Module 类来管理模块的类工厂。

    #include "pch.h" // Use stdafx.h in Visual Studio 2017 and earlier
    #include <wrl\module.h>using namespace Microsoft::WRL;#if !defined(__WRL_CLASSIC_COM__)
    STDAPI DllGetActivationFactory(_In_ HSTRING activatibleClassId, _COM_Outptr_ IActivationFactory** factory)
    {return Module<InProc>::GetModule().GetActivationFactory(activatibleClassId, factory);
    }
    #endif#if !defined(__WRL_WINRT_STRICT__)
    STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, _COM_Outptr_ void** ppv)
    {return Module<InProc>::GetModule().GetClassObject(rclsid, riid, ppv);
    }
    #endifSTDAPI DllCanUnloadNow()
    {return Module<InProc>::GetModule().Terminate() ? S_OK : S_FALSE;
    }STDAPI_(BOOL) DllMain(_In_opt_ HINSTANCE hinst, DWORD reason, _In_opt_ void*)
    {if (reason == DLL_PROCESS_ATTACH){DisableThreadLibraryCalls(hinst);}return TRUE;
    }
  7. 向该项目添加“模块定义文件 (.def)”文件。 为该文件命名,例如,CalculatorComponent.def。 此文件为链接器提供了要导出的函数的名称。 打开项目的“属性页”对话框,然后在“配置属性”>“链接器”>“输入”下,将“模块定义文件”属性设置为 DEF 文件。

  8. 将此代码添加到 CalculatorComponent.def:

    LIBRARYEXPORTSDllGetActivationFactory PRIVATEDllGetClassObject       PRIVATEDllCanUnloadNow         PRIVATE
  9. 将 runtimeobject.lib 添加到链接器行。

从桌面应用程序使用 COM 组件

1. 向 Windows 注册表注册 COM 组件。 若要实现此操作,请创建一个注册表项文件,将其命名为 RegScript.reg,并添加以下文本。 将 <dll-path> 替换为 DLL 的路径,例如 C:\temp\WRLClassicCOM\Debug\CalculatorComponent.dll。

Windows Registry Editor Version 5.00[HKEY_CLASSES_ROOT\Wow6432Node\CLSID\{E68F5EDD-6257-4E72-A10B-4067ED8E85F2}]
@="CalculatorComponent Class"[HKEY_CLASSES_ROOT\Wow6432Node\CLSID\{E68F5EDD-6257-4E72-A10B-4067ED8E85F2}\InprocServer32]
@="<dll-path>"
"ThreadingModel"="Apartment"[HKEY_CLASSES_ROOT\Wow6432Node\CLSID\{E68F5EDD-6257-4E72-A10B-4067ED8E85F2}\Programmable][HKEY_CLASSES_ROOT\Wow6432Node\CLSID\{E68F5EDD-6257-4E72-A10B-4067ED8E85F2}\TypeLib]
@="{9D3E6826-CB8E-4D86-8B14-89F0D7EFCD01}"[HKEY_CLASSES_ROOT\Wow6432Node\CLSID\{E68F5EDD-6257-4E72-A10B-4067ED8E85F2}\Version]
@="1.0"

2. 运行 RegScript.reg 或将其添加到项目的生成后事件。 

3. 向该解决方案添加“Win32 控制台应用程序”项目。 为该项目命名,例如 Calculator。

4. 用此代码替换 Calculator.cpp 的内容:

#include "pch.h" // Use stdafx.h in Visual Studio 2017 and earlier#include "..\CalculatorComponent\CalculatorComponent_h.h"const IID IID_ICalculatorComponent = {0x0DBABB94,0xCE99,0x42F7,0xAC,0xBD,0xE6,0x98,0xB2,0x33,0x2C,0x60};
const CLSID CLSID_CalculatorComponent = {0xE68F5EDD,0x6257,0x4E72,0xA1,0x0B,0x40,0x67,0xED,0x8E,0x85,0xF2};// Prints an error string for the provided source code line and HRESULT
// value and returns the HRESULT value as an int.
int PrintError(unsigned int line, HRESULT hr)
{wprintf_s(L"ERROR: Line:%d HRESULT: 0x%X\n", line, hr);return hr;
}int wmain()
{HRESULT hr;// Initialize the COM library.hr = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);if (FAILED(hr)){return PrintError(__LINE__, hr);}ICalculatorComponent* calc = nullptr; // Interface to COM component.// Create the CalculatorComponent object.hr = CoCreateInstance(CLSID_CalculatorComponent, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&calc));if (SUCCEEDED(hr)){// Test the component by adding two numbers.int result;hr = calc->Add(4, 5, &result);if (FAILED(hr)){PrintError(__LINE__, hr);}else{wprintf_s(L"result = %d\n", result);}// Free the CalculatorComponent object.calc->Release();}else{// Object creation failed. Print a message.PrintError(__LINE__, hr);}// Free the COM library.CoUninitialize();return hr;
}
/* Output:
result = 9
*/
可靠编程

本文档使用标准 COM 函数来演示可使用 Windows 运行时 C++ 模板库来创建 COM 组件并使其可用于支持 COM 的任何技术。 还可在桌面应用程序中使用 Windows 运行时 C++ 模板库类型(如 Microsoft::WRL::ComPtr)来管理 COM 及其他对象的生存期。 以下代码使用 Windows 运行时 C++ 模板库来管理 ICalculatorComponent 指针的生存期。 CoInitializeWrapper 类是一种 RAII 包装,可保证 COM 库已释放,并保证 COM 库的生存期长于 ComPtr 智能指针对象。

#include "pch.h" // Use stdafx.h in Visual Studio 2017 and earlier
#include <wrl.h>#include "..\CalculatorComponent\CalculatorComponent_h.h"using namespace Microsoft::WRL;const IID IID_ICalculatorComponent = {0x0DBABB94,0xCE99,0x42F7,0xAC,0xBD,0xE6,0x98,0xB2,0x33,0x2C,0x60};
const CLSID CLSID_CalculatorComponent = {0xE68F5EDD,0x6257,0x4E72,0xA1,0x0B,0x40,0x67,0xED,0x8E,0x85,0xF2};// Prints an error string for the provided source code line and HRESULT
// value and returns the HRESULT value as an int.
int PrintError(unsigned int line, HRESULT hr)
{wprintf_s(L"ERROR: Line:%d HRESULT: 0x%X\n", line, hr);return hr;
}int wmain()
{HRESULT hr;// RAII wrapper for managing the lifetime of the COM library.class CoInitializeWrapper{HRESULT _hr;public:CoInitializeWrapper(DWORD flags){_hr = CoInitializeEx(nullptr, flags);}~CoInitializeWrapper(){if (SUCCEEDED(_hr)){CoUninitialize();}}operator HRESULT(){return _hr;}};// Initialize the COM library.CoInitializeWrapper initialize(COINIT_APARTMENTTHREADED);if (FAILED(initialize)){return PrintError(__LINE__, initialize);}ComPtr<ICalculatorComponent> calc; // Interface to COM component.// Create the CalculatorComponent object.hr = CoCreateInstance(CLSID_CalculatorComponent, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(calc.GetAddressOf()));if (SUCCEEDED(hr)){// Test the component by adding two numbers.int result;hr = calc->Add(4, 5, &result);if (FAILED(hr)){return PrintError(__LINE__, hr);}wprintf_s(L"result = %d\n", result);}else{// Object creation failed. Print a message.return PrintError(__LINE__, hr);}return 0;
}

这篇关于windows C++-WRL 创建传统型 COM 组件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1107712

相关文章

Vue和React受控组件的区别小结

《Vue和React受控组件的区别小结》本文主要介绍了Vue和React受控组件的区别小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学... 目录背景React 的实现vue3 的实现写法一:直接修改事件参数写法二:通过ref引用 DOMVu

C++统计函数执行时间的最佳实践

《C++统计函数执行时间的最佳实践》在软件开发过程中,性能分析是优化程序的重要环节,了解函数的执行时间分布对于识别性能瓶颈至关重要,本文将分享一个C++函数执行时间统计工具,希望对大家有所帮助... 目录前言工具特性核心设计1. 数据结构设计2. 单例模式管理器3. RAII自动计时使用方法基本用法高级用法

深入解析C++ 中std::map内存管理

《深入解析C++中std::map内存管理》文章详解C++std::map内存管理,指出clear()仅删除元素可能不释放底层内存,建议用swap()与空map交换以彻底释放,针对指针类型需手动de... 目录1️、基本清空std::map2️、使用 swap 彻底释放内存3️、map 中存储指针类型的对象

Spring创建Bean的八种主要方式详解

《Spring创建Bean的八种主要方式详解》Spring(尤其是SpringBoot)提供了多种方式来让容器创建和管理Bean,@Component、@Configuration+@Bean、@En... 目录引言一、Spring 创建 Bean 的 8 种主要方式1. @Component 及其衍生注解

C++ STL-string类底层实现过程

《C++STL-string类底层实现过程》本文实现了一个简易的string类,涵盖动态数组存储、深拷贝机制、迭代器支持、容量调整、字符串修改、运算符重载等功能,模拟标准string核心特性,重点强... 目录实现框架一、默认成员函数1.默认构造函数2.构造函数3.拷贝构造函数(重点)4.赋值运算符重载函数

C++ vector越界问题的完整解决方案

《C++vector越界问题的完整解决方案》在C++开发中,std::vector作为最常用的动态数组容器,其便捷性与性能优势使其成为处理可变长度数据的首选,然而,数组越界访问始终是威胁程序稳定性的... 目录引言一、vector越界的底层原理与危害1.1 越界访问的本质原因1.2 越界访问的实际危害二、基

MySQL 数据库表操作完全指南:创建、读取、更新与删除实战

《MySQL数据库表操作完全指南:创建、读取、更新与删除实战》本文系统讲解MySQL表的增删查改(CURD)操作,涵盖创建、更新、查询、删除及插入查询结果,也是贯穿各类项目开发全流程的基础数据交互原... 目录mysql系列前言一、Create(创建)并插入数据1.1 单行数据 + 全列插入1.2 多行数据

MySQL 临时表创建与使用详细说明

《MySQL临时表创建与使用详细说明》MySQL临时表是存储在内存或磁盘的临时数据表,会话结束时自动销毁,适合存储中间计算结果或临时数据集,其名称以#开头(如#TempTable),本文给大家介绍M... 目录mysql 临时表详细说明1.定义2.核心特性3.创建与使用4.典型应用场景5.生命周期管理6.注

c++日志库log4cplus快速入门小结

《c++日志库log4cplus快速入门小结》文章浏览阅读1.1w次,点赞9次,收藏44次。本文介绍Log4cplus,一种适用于C++的线程安全日志记录API,提供灵活的日志管理和配置控制。文章涵盖... 目录简介日志等级配置文件使用关于初始化使用示例总结参考资料简介log4j 用于Java,log4c

MySQL的触发器全解析(创建、查看触发器)

《MySQL的触发器全解析(创建、查看触发器)》MySQL触发器是与表关联的存储程序,当INSERT/UPDATE/DELETE事件发生时自动执行,用于维护数据一致性、日志记录和校验,优点包括自动执行... 目录触发器的概念:创建触www.chinasem.cn发器:查看触发器:查看当前数据库的所有触发器的定