如何:使用 WRL 创建传统型 COM 组件

可以使用的 Windows 运行时 C++ 模板库 (WRL) 除了外使用此 Windows 应用商店 应用的,创建基本的经典 COM 组件用于应用程序,桌面。 对于 COM 组件的创建,与 WRL 相比 ATL 可能少代码。 有关 WRL 支持的子集,请参见 Windows 运行时 C++ 模板库 (WRL)COM 的信息。

演示如何使用 WRL 创建基本 组件。 尽管您可以使用最符合您的需要,该文档还演示一种基本方式注册和使用从桌面应用程序的 COM 组件的部署机制。

演示如何使用 WRL 创建基本classic COM c 组件。

  1. 在 Visual Studio 中创建新的 Blank Solution 项目 例如,将项目命名为WRLClassicCOM。

  2. 向解决方案添加新的 Win32 Project 项目。 例如,将项目命名为CalculatorComponent。 在 应用程序设置 选项卡,选择 DLL(D)

  3. 将属性组添加到项目Midl File (.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 而不是。IInspectableIInspectable (仅对 应用商店 组件) 创建 CoCreatableClass 应用。可以使用函数的类的工厂 CoCreateInstance

    #include "stdafx.h"
    
    #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 "stdafx.h"
    #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);
    }
    #endif
    
    STDAPI 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。 此文件给出了添加要导出到此文件的函数名。

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

    LIBRARY
    
    EXPORTS
        DllGetActivationFactory PRIVATE
        DllGetClassObject       PRIVATE
        DllCanUnloadNow         PRIVATE
    
  9. 添加 runtimeobject.lib 到链接器行。 要了解详细信息,请参阅 用作链接器输入的 .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 Console Application 项目添加到解决方案中 将Calculator项目命名为 SampleDatabaseWalkthrough。

  4. 使用下面的代码替换 Calculator.cpp 内容:

    #include "stdafx.h"
    
    #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 函数说明,可以使用 WRL 创作 COM 组件并使其可用任何启用 COM 的技术。 在桌面应用程序中使用 WRL 类型 (如 Microsoft::WRL::ComPtr 生存期管理 COM 和其他对象。 以下代码使用 WRL 管理 ICalculatorComponent 指针的生存期。 CoInitializeWrapper 类可保证的 RAII 包装 COM 库被释放并保证 COM 库的生存期活得比 ComPtr 智能长指针的对象。

#include "stdafx.h"
#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)