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

相关文章

Linux线程之线程的创建、属性、回收、退出、取消方式

《Linux线程之线程的创建、属性、回收、退出、取消方式》文章总结了线程管理核心知识:线程号唯一、创建方式、属性设置(如分离状态与栈大小)、回收机制(join/detach)、退出方法(返回/pthr... 目录1. 线程号2. 线程的创建3. 线程属性4. 线程的回收5. 线程的退出6. 线程的取消7.

创建Java keystore文件的完整指南及详细步骤

《创建Javakeystore文件的完整指南及详细步骤》本文详解Java中keystore的创建与配置,涵盖私钥管理、自签名与CA证书生成、SSL/TLS应用,强调安全存储及验证机制,确保通信加密和... 目录1. 秘密键(私钥)的理解与管理私钥的定义与重要性私钥的管理策略私钥的生成与存储2. 证书的创建与

c++ 类成员变量默认初始值的实现

《c++类成员变量默认初始值的实现》本文主要介绍了c++类成员变量默认初始值,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录C++类成员变量初始化c++类的变量的初始化在C++中,如果使用类成员变量时未给定其初始值,那么它将被

C++中NULL与nullptr的区别小结

《C++中NULL与nullptr的区别小结》本文介绍了C++编程中NULL与nullptr的区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编... 目录C++98空值——NULLC++11空值——nullptr区别对比示例 C++98空值——NUL

C++ Log4cpp跨平台日志库的使用小结

《C++Log4cpp跨平台日志库的使用小结》Log4cpp是c++类库,本文详细介绍了C++日志库log4cpp的使用方法,及设置日志输出格式和优先级,具有一定的参考价值,感兴趣的可以了解一下... 目录一、介绍1. log4cpp的日志方式2.设置日志输出的格式3. 设置日志的输出优先级二、Window

从入门到精通C++11 <chrono> 库特性

《从入门到精通C++11<chrono>库特性》chrono库是C++11中一个非常强大和实用的库,它为时间处理提供了丰富的功能和类型安全的接口,通过本文的介绍,我们了解了chrono库的基本概念... 目录一、引言1.1 为什么需要<chrono>库1.2<chrono>库的基本概念二、时间段(Durat

C++20管道运算符的实现示例

《C++20管道运算符的实现示例》本文简要介绍C++20管道运算符的使用与实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录标准库的管道运算符使用自己实现类似的管道运算符我们不打算介绍太多,因为它实际属于c++20最为重要的

Visual Studio 2022 编译C++20代码的图文步骤

《VisualStudio2022编译C++20代码的图文步骤》在VisualStudio中启用C++20import功能,需设置语言标准为ISOC++20,开启扫描源查找模块依赖及实验性标... 默认创建Visual Studio桌面控制台项目代码包含C++20的import方法。右键项目的属性:

c++中的set容器介绍及操作大全

《c++中的set容器介绍及操作大全》:本文主要介绍c++中的set容器介绍及操作大全,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录​​一、核心特性​​️ ​​二、基本操作​​​​1. 初始化与赋值​​​​2. 增删查操作​​​​3. 遍历方

解析C++11 static_assert及与Boost库的关联从入门到精通

《解析C++11static_assert及与Boost库的关联从入门到精通》static_assert是C++中强大的编译时验证工具,它能够在编译阶段拦截不符合预期的类型或值,增强代码的健壮性,通... 目录一、背景知识:传统断言方法的局限性1.1 assert宏1.2 #error指令1.3 第三方解决