如何:使用 WRL 建立傳統 COM 元件
除了為 Windows 市集 應用程式使用 Windows 執行階段 C++ 範本庫 (WRL) 外,您也可以使用它為傳統型應用程式建立基本的一般 COM 元件,。 對於 COM 元件的建立, WRL 可能比 ATL 需要較少的程式碼。 如需 WRL 支援,請參閱 Windows Runtime C++ Template Library (WRL) COM 資訊的子集。
本文件將示範如何使用 WRL 建立基本的 COM 元件。 雖然您可以使用最符合您需求的部署機制,此文件也顯示使用基本方法從傳統型應用程式上註冊並使用 COM 元件。
使用 WRL 以建立基本傳統 COM 元件
在 Visual Studio 中建立 空白方案 專案。 命名專案,例如WRLClassicCOM。
將新的 Win32 專案加入至方案。 命名專案,例如 CalculatorComponent。 在 [應用程式設定] 索引標籤上,選取 [DLL]。
將**Midl File (.idl)**檔案加入至專案檔。 命名檔案,例如,CalculatorComponent.idl。
將此程式碼加入至 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; } };
在 CalculatorComponent.cpp,請定義 CalculatorComponent 類別。 CalculatorComponent 類別繼承自 Microsoft::WRL::RuntimeClass。 Microsoft::WRL::RuntimeClassFlags<ClassicCom> 指定此類別是衍生自 IUnknown 而不是 IInspectable。(IInspectable 只在 市集 應用程式元件可取得)。 CoCreatableClass 建立可以搭配函式如CoCreateInstance 的類別的 Factory。
#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);
使用下列程式碼取代 dllmain.cpp 的程式碼。 這個檔案會定義 DLL 匯出函式。 這些函式會使用 Microsoft::WRL::Module 類別管理模組的類別 Factory。
#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; }
將 [模組定義檔 (.def)] 檔案加入至專案。 命名檔案,例如,CalculatorComponent.def。 此檔案給予連結器欲匯出的函式名稱。
將此程式碼加入至 CalculatorComponent.def:
LIBRARY EXPORTS DllGetActivationFactory PRIVATE DllGetClassObject PRIVATE DllCanUnloadNow PRIVATE
將 runtimeobject.lib 加入至連結器列。 若要了解如何的詳細資訊,請參閱 .Lib 檔做為連結器輸入。
使用傳統型應用程式的 COM 元件
向 Windows 註冊的 COM 元件。 若要這麼做,請建立註冊項目檔案,並將它命名為 RegScript.reg,並加入下列文字。 使用 DLL 路徑來取代 <dll-path> (例如, 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"
執行 RegScript.reg 或將它加入至專案的 [建置後事件]。 如需詳細資訊,請參閱建置前事件/建置後事件命令列對話方塊。
將 Win32 主控台應用程式 專案加入至方案。 命名專案,例如,Calculator。
若要使用這段程式碼取代 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;
}