🎯 Load an ONNX model from C++ with the legacy Windows ML API
Scope: legacy API. This article uses the
Windows.AI.MachineLearningAPI introduced with Windows 10 version 1809. It has been superseded by the current Windows ML APIs. For new apps, follow Microsoft’s current Windows ML getting-started guide. The code below only loads a model; it does not run inference. For a complete inference example, see Microsoft’s C++ desktop tutorial.
✅ Preparation
◾ System Requirements
- Windows 10 (1809+) or Windows 11
- Visual Studio 2019 or later (Community edition is fine)
- C++/WinRT integration for the legacy Windows SDK
- Windows SDK 10.0.17763.0 or higher
✅ Project Configuration
For this legacy API, use Windows 10 version 1809 (build 17763) or later, a compatible Windows SDK, Visual Studio with the C++ desktop workload, and C++/WinRT. Do not confuse packages for current Windows ML with dependencies for this legacy API. Check the deployment guide for current API packages and deployment requirements.
✅ Sample Code
This is a model-loading check only. ONNX models have model-specific input names, types, and shapes; calling
EvaluateAsyncwithout binding required inputs will generally not run inference.
main.cpp
Set model.onnx to the actual absolute path. A relative path may be resolved against the current working directory, which is not necessarily the executable’s directory.
| |
✅ Supplement: Example of binding model inputs
The following fragment shows the shape of an input binding. Adapt data_0, the type, shape, and values to the model. This fragment alone is not a complete program that loads a model and returns inference results.
| |
Output names and types are also model-specific. Inspect the ONNX inputs and outputs with a tool such as Netron, then bind values that match the model.
Microsoft Learn: TensorFloat::CreateFromArray documents the API used in the binding fragment.
✅ Summary
This sample only demonstrates model loading with the legacy Windows.AI.MachineLearning API. It does not guarantee GPU execution or successful inference for a particular model. For new development, choose the current Windows ML APIs and verify package and OS requirements in the official guide.
✅ Alternatives: For those who do not want to use WinRT
- By using Microsoft’s
ONNX Runtime, you can handle ONNX models from C++ entirely without WinRT. - It supports cross-platform, allowing common code for Windows/Linux.
📌 Conclusion
This sample only demonstrates model loading with the legacy Windows.AI.MachineLearning API. It does not guarantee GPU execution or successful inference for a particular model. For new development, choose the current Windows ML APIs and verify package and OS requirements in the official guide.
![Featured image of post [Legacy API] Load an ONNX Model from C++ with Windows ML](/p/c-%E3%81%8B%E3%82%89microsoft.windows.ai%E3%82%92%E5%91%BC%E3%81%B3%E5%87%BA%E3%81%99%E6%96%B9%E6%B3%95/img_hu4989369921964388449.webp)