Important
Windows ML 執行時 API 目前仍處於實驗階段,尚未支援用於生產環境。 嘗試此 API 的應用程式不應被發佈到 Microsoft Store。
本主題將教你如何配置原生 C++ 專案,使其使用 Runtime API 並建立實 IWinMLRuntime 例。 繼續使用 Windows ML Runtime API 執行模型,進行模型載入、張量綁定及推論。
Prerequisites
- 受
Microsoft.Windows.AI.MachineLearning套件支援的 Windows 版本。 請參閱 Windows 機器學習部署需求。 - Visual Studio 2022 或更新版本,支援使用 C++ 的桌面開發工作負載。
- 一個原生的 C++ 控制台專案。
-
實驗版
2.7.2021-experimentalMicrosoft.Windows.AI.MachineLearning NuGet 套件。 - 以下頁面的範例程式碼需要 C++20 和 Microsoft.Windows.CppWinRT NuGet 套件。
Note
C++20 和 C++/WinRT 是這些文件範例的必要條件,而非執行時 API 的必要條件。 執行階段 API 是一種原生的 COM 風格 ABI,也可以依據該應用程式的語言需求,透過原始 COM、WRL、WIL 或其他 COM 輔助工具由 C 或 C++ 取用。
CPU 執行目標是基準路徑。 GPU 和 NPU 的可用性取決於裝置、平台能力以及為你的應用程式安裝的執行後端。
設定原生 NuGet 還原
原生 Visual C++ 專案需要 NuGet 目標框架識別項,因此套件還原會選擇原生的 Windows 資產。 在Microsoft.Cpp.*檔案頂端附近、首次.vcxproj匯入之前,加入此屬性群組:
<PropertyGroup Label="NuGet">
<RestoreProjectStyle>PackageReference</RestoreProjectStyle>
<NuGetTargetMoniker>native,Version=v0.0</NuGetTargetMoniker>
<NuGetTargetPlatformIdentifier>Windows</NuGetTargetPlatformIdentifier>
<NuGetTargetPlatformVersion>$(WindowsTargetPlatformVersion)</NuGetTargetPlatformVersion>
</PropertyGroup>
可透過 PackageReference 或 Microsoft.Windows.AI.MachineLearning 安裝 套件。 要建立在這些頁面中的範例,也請安裝Microsoft.Windows.CppWinRT並設定 C++ 語言標準為 ISO C++20 標準(/std:c++20)。 Windows ML 套件提供執行階段標頭、匯入程式庫及自成一體的 DLL;C++/WinRT 提供僅供範例程式碼使用的 winrt::com_ptr、winrt::check_hresult 及 <winrt/base.h> 便利功能。
關於 CMake 與部署選項,請參見 自包含安裝。
初始化執行階段
以下列程式碼取代 main.cpp:
// Copyright (C) Microsoft Corporation. All rights reserved.
#include <Windows.h>
#include <winrt/base.h>
#include <WinMLRuntime.h>
#pragma comment(lib, "windowsapp.lib")
int wmain()
{
winrt::com_ptr<IWinMLRuntime> runtime;
winrt::check_hresult(WinMLCreateRuntime(
__uuidof(IWinMLRuntime),
runtime.put_void()));
return 0;
}
針對與套件資產相符的架構進行建置,例如 Release|x64。 成功建置證實 NuGet 還原已找到執行時標頭和匯入函式庫,並將所需的 DLL 複製到執行檔旁邊。