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

相关文章

C++ move 的作用详解及陷阱最佳实践

《C++move的作用详解及陷阱最佳实践》文章详细介绍了C++中的`std::move`函数的作用,包括为什么需要它、它的本质、典型使用场景、以及一些常见陷阱和最佳实践,感兴趣的朋友跟随小编一起看... 目录C++ move 的作用详解一、一句话总结二、为什么需要 move?C++98/03 的痛点⚡C++

JavaWeb项目创建、部署、连接数据库保姆级教程(tomcat)

《JavaWeb项目创建、部署、连接数据库保姆级教程(tomcat)》:本文主要介绍如何在IntelliJIDEA2020.1中创建和部署一个JavaWeb项目,包括创建项目、配置Tomcat服务... 目录简介:一、创建项目二、tomcat部署1、将tomcat解压在一个自己找得到路径2、在idea中添加

详解C++ 存储二进制数据容器的几种方法

《详解C++存储二进制数据容器的几种方法》本文主要介绍了详解C++存储二进制数据容器,包括std::vector、std::array、std::string、std::bitset和std::ve... 目录1.std::vector<uint8_t>(最常用)特点:适用场景:示例:2.std::arra

C++构造函数中explicit详解

《C++构造函数中explicit详解》explicit关键字用于修饰单参数构造函数或可以看作单参数的构造函数,阻止编译器进行隐式类型转换或拷贝初始化,本文就来介绍explicit的使用,感兴趣的可以... 目录1. 什么是explicit2. 隐式转换的问题3.explicit的使用示例基本用法多参数构造

Java利用Spire.Doc for Java实现在模板的基础上创建Word文档

《Java利用Spire.DocforJava实现在模板的基础上创建Word文档》在日常开发中,我们经常需要根据特定数据动态生成Word文档,本文将深入探讨如何利用强大的Java库Spire.Do... 目录1. Spire.Doc for Java 库介绍与安装特点与优势Maven 依赖配置2. 通过替换

C++,C#,Rust,Go,Java,Python,JavaScript的性能对比全面讲解

《C++,C#,Rust,Go,Java,Python,JavaScript的性能对比全面讲解》:本文主要介绍C++,C#,Rust,Go,Java,Python,JavaScript性能对比全面... 目录编程语言性能对比、核心优势与最佳使用场景性能对比表格C++C#RustGoJavapythonjav

C++打印 vector的几种方法小结

《C++打印vector的几种方法小结》本文介绍了C++中遍历vector的几种方法,包括使用迭代器、auto关键字、typedef、计数器以及C++11引入的范围基础循环,具有一定的参考价值,感兴... 目录1. 使用迭代器2. 使用 auto (C++11) / typedef / type alias

JavaWeb 中的 Filter组件详解

《JavaWeb中的Filter组件详解》本文详细介绍了JavaWeb中的Filter组件,包括其基本概念、工作原理、核心接口和类、配置方式以及常见应用示例,Filter可以实现请求预处理、响应后... 目录JavaWeb 中的 Filter 详解1. Filter 基本概念1.1 什么是 Filter1.

C++ scoped_ptr 和 unique_ptr对比分析

《C++scoped_ptr和unique_ptr对比分析》本文介绍了C++中的`scoped_ptr`和`unique_ptr`,详细比较了它们的特性、使用场景以及现代C++推荐的使用`uni... 目录1. scoped_ptr基本特性主要特点2. unique_ptr基本用法3. 主要区别对比4. u

C++11中的包装器实战案例

《C++11中的包装器实战案例》本文给大家介绍C++11中的包装器实战案例,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录引言1.std::function1.1.什么是std::function1.2.核心用法1.2.1.包装普通函数1.2.