从 WRL 迁移到 C++/WinRT

本主题演示如何将 Windows 运行时 C++ 模板库 (WRL) 代码移植到其在 C++/WinRT中的等效代码。

移植到 C++/WinRT 的第一步是将 C++/WinRT 支持手动添加到项目(请参阅 Visual Studio 对 C++/WinRT的支持)。 为此,请将 Microsoft.Windows.CppWinRT NuGet 包 安装到项目中。 在 Visual Studio 中打开项目,单击“项目>管理 NuGet 包...”>浏览,在搜索框中键入或粘贴 Microsoft.Windows.CppWinRT,选择搜索结果中的项,然后单击 安装 安装该项目的包。 此更改的一个效果是,在项目中关闭对 C++/CX 的支持。 如果在项目中使用 C++/CX,则可以关闭支持,并将 C++/CX 代码更新为 C++/WinRT(请参阅 从 C++/CX移动到 C++/WinRT)。 或者,可以在项目属性中重新启用支持(C/C++>常规>使用 Windows 运行时扩展>是(/ZW)),并首先专注于移植 WRL 代码。 C++/CX 和 C++/WinRT 代码可以共存在同一项目中,但 XAML 编译器支持和 Windows 运行时组件除外(请参阅 从 C++/CX移动到 C++/WinRT)。

将项目属性 常规>目标平台版本 设置为 10.0.17134.0(Windows 10 版本 1803)或更高版本。

在预编译头文件(通常为 pch.h)中加入 winrt/base.h

#include <winrt/base.h>

如果你包含了任何 C++/WinRT 投射的 Windows API 标头(例如,winrt/Windows.Foundation.h),那么就不需要像这样显式地包含 winrt/base.h,因为它将自动为你包含。

移植 WRL COM 智能指针(Microsoft::WRL::ComPtr)

将使用 Microsoft::WRL::ComPtr<T> 的代码移植为使用 winrt::com_ptr<T>的代码。 下面是之前和之后的代码示例。 在版本之后的中,com_ptr::put 成员函数检索其底层原始指针,以便能够设置它。

ComPtr<IDXGIAdapter1> previousDefaultAdapter;
DX::ThrowIfFailed(m_dxgiFactory->EnumAdapters1(0, &previousDefaultAdapter));
winrt::com_ptr<IDXGIAdapter1> previousDefaultAdapter;
winrt::check_hresult(m_dxgiFactory->EnumAdapters1(0, previousDefaultAdapter.put()));

重要

如果你有一个 winrt::com_ptr已经设置好(其内部原始指针已有目标),并且想要重新设置指向其他对象,则首先需要为其分配 nullptr,如下面的代码示例所示。 如果不这么做,已设置的 com_ptr 将通过断言其内部指针不为 null 来引起你的注意(当你调用 com_ptr::putcom_ptr::put_void时)。

winrt::com_ptr<IDXGISwapChain1> m_pDXGISwapChain1;
...
// We execute the code below each time the window size changes.
m_pDXGISwapChain1 = nullptr; // Important because we're about to re-seat 
winrt::check_hresult(
    m_pDxgiFactory->CreateSwapChainForHwnd(
        m_pCommandQueue.get(), // For Direct3D 12, this is a pointer to a direct command queue, and not to the device.
        m_hWnd,
        &swapChainDesc,
        nullptr,
        nullptr,
        m_pDXGISwapChain1.put())
);

在下一个示例中(在 版本之后的 中),com_ptr::put_void 成员函数将检索基础原始指针,作为 void 指针的指针。

ComPtr<ID3D12Debug> debugController;
if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&debugController))))
{
    debugController->EnableDebugLayer();
}
winrt::com_ptr<ID3D12Debug> debugController;
if (SUCCEEDED(D3D12GetDebugInterface(__uuidof(debugController), debugController.put_void())))
{
    debugController->EnableDebugLayer();
}

ComPtr::Get 替换为 com_ptr::get

m_d3dDevice->CreateDepthStencilView(m_depthStencil.Get(), &dsvDesc, m_dsvHeap->GetCPUDescriptorHandleForHeapStart());
m_d3dDevice->CreateDepthStencilView(m_depthStencil.get(), &dsvDesc, m_dsvHeap->GetCPUDescriptorHandleForHeapStart());

如果需要将底层原始指针传递给期望一个指向 IUnknown的函数,请使用 winrt::get_unknown 自由函数,如下例所示。

ComPtr<IDXGISwapChain1> swapChain;
DX::ThrowIfFailed(
    m_dxgiFactory->CreateSwapChainForCoreWindow(
        m_commandQueue.Get(),
        reinterpret_cast<IUnknown*>(m_window.Get()),
        &swapChainDesc,
        nullptr,
        &swapChain
    )
);
winrt::agile_ref<winrt::Windows::UI::Core::CoreWindow> m_window; 
winrt::com_ptr<IDXGISwapChain1> swapChain;
winrt::check_hresult(
    m_dxgiFactory->CreateSwapChainForCoreWindow(
        m_commandQueue.get(),
        winrt::get_unknown(m_window.get()),
        &swapChainDesc,
        nullptr,
        swapChain.put()
    )
);

移植 WRL 模块 (Microsoft::WRL::Module)

本部分与使用 Microsoft::WRL::Module 类型的移植代码相关。

你可以逐步将C++/WinRT 代码添加到使用 WRL 实现组件的现有项目中,并且现有 WRL 类将继续受支持。 本部分介绍如何操作。

在 Visual Studio 中创建新的 Windows 运行时组件(C++/WinRT) 项目类型并进行构建,然后会自动生成文件 Generated Files\module.g.cpp。 该文件包含两个有用的C++/WinRT 函数的定义(下面列出),你可以复制和添加到项目。 这些函数是 WINRT_CanUnloadNowWINRT_GetActivationFactory,正如你所看到的,它们在条件允许的情况下调用 WRL,以在你移植过程的任意阶段提供支持。

HRESULT WINRT_CALL WINRT_CanUnloadNow()
{
#ifdef _WRL_MODULE_H_
    if (!::Microsoft::WRL::Module<::Microsoft::WRL::InProc>::GetModule().Terminate())
    {
        return S_FALSE;
    }
#endif

    if (winrt::get_module_lock())
    {
        return S_FALSE;
    }

    winrt::clear_factory_cache();
    return S_OK;
}

HRESULT WINRT_CALL WINRT_GetActivationFactory(HSTRING classId, void** factory)
{
    try
    {
        *factory = nullptr;
        wchar_t const* const name = WINRT_WindowsGetStringRawBuffer(classId, nullptr);

        if (0 == wcscmp(name, L"MoveFromWRLTest.Class"))
        {
            *factory = winrt::detach_abi(winrt::make<winrt::MoveFromWRLTest::factory_implementation::Class>());
            return S_OK;
        }

#ifdef _WRL_MODULE_H_
        return ::Microsoft::WRL::Module<::Microsoft::WRL::InProc>::GetModule().GetActivationFactory(classId, reinterpret_cast<::IActivationFactory**>(factory));
#else
        return winrt::hresult_class_not_available().to_abi();
#endif
    }
    catch (...) { return winrt::to_hresult(); }
}

在项目中拥有这些函数后,无需直接调用 Module::GetActivationFactory,而是调用 WINRT_GetActivationFactory(在内部调用 WRL 函数)。 下面是之前和之后的代码示例。

HRESULT WINAPI DllGetActivationFactory(_In_ HSTRING activatableClassId, _Out_ ::IActivationFactory **factory)
{
    auto & module = Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule();
    return module.GetActivationFactory(activatableClassId, factory);
}
HRESULT __stdcall WINRT_GetActivationFactory(HSTRING activatableClassId, void** factory);
HRESULT WINAPI DllGetActivationFactory(_In_ HSTRING activatableClassId, _Out_ ::IActivationFactory **factory)
{
    return WINRT_GetActivationFactory(activatableClassId, reinterpret_cast<void**>(factory));
}

请调用 WINRT_CanUnloadNow(该函数将内部调用 WRL 函数),而不是直接调用 Module::Terminate。 下面是之前和之后的代码示例。

HRESULT __stdcall DllCanUnloadNow(void)
{
    auto &module = Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule();
    HRESULT hr = (module.Terminate() ? S_OK : S_FALSE);
    if (hr == S_OK)
    {
        hr = ...
    }
    return hr;
}
HRESULT __stdcall WINRT_CanUnloadNow();
HRESULT __stdcall DllCanUnloadNow(void)
{
    HRESULT hr = WINRT_CanUnloadNow();
    if (hr == S_OK)
    {
        hr = ...
    }
    return hr;
}

移植 Microsoft::WRL::Wrappers 包装器

本部分与使用 Microsoft::WRL::Wrappers 包装器的移植代码相关。

如下表所示,若要替换线程帮助程序,我们建议使用标准C++线程支持库。 WRL 包装器中的一对一映射可能会误导,因为你要根据自己的需求做出选择。 此外,某些看似明显的映射类型是 C++20 标准的新增功能,因此,如果尚未升级,这些类型将是不切实际的。

类型 移植说明文档
CriticalSection 类 使用 线程支持库
事件类 (WRL) 使用 winrt::event 结构模板
HandleT 类 使用 winrt::handle 结构体winrt::file_handle 结构体
HString 类 使用 winrt::hstring 结构
HStringReference 类 不需要替代项,因为 C++/WinRT 以内部方式处理此问题,其效率与 HStringReference 一样高,而且无需您费心考虑。
Mutex 类 使用 线程支持库
RoInitializeWrapper 类 使用 winrt::init_apartmentwinrt::uninit_apartment;或编写自己的简单封装 CoInitializeExCoUninitialize
信号灯类 使用 线程支持库
SRWLock 类 使用 线程支持库

重要 API