Windows 10环境下使用Microsoft.ML加载ONNX模型提示无法加载onnxruntime.dll的问题求助
Windows 10环境下使用Microsoft.ML加载ONNX模型提示无法加载onnxruntime.dll的问题求助
大家好,我遇到了一个跨Windows版本的ONNX模型加载问题,折腾很久没找到解决办法,想请大家帮忙看看:
问题背景
我在自己的Windows 11(版本10.0.26200)电脑上,从PyTorch导出ONNX模型,再用C#的Microsoft.ML加载运行完全正常,但在客户的Windows 10(10.0.19045)电脑上却报错,而且客户的系统无法更新,这让我特别头疼。
最小复现步骤
1. 用PyTorch导出ONNX模型
先通过Python代码导出一个极简的拼接模型:
import torch import torch.nn as nn class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, *inputs): concatenated = torch.cat(inputs, dim=-1) return concatenated model: MyModel = MyModel() torch.onnx.export( model, (torch.ones(1, 342), torch.ones(1, 342)), "model.onnx", export_params=True )
2. 用C#的Microsoft.ML加载模型
编写C#控制台程序尝试加载该模型:
using Microsoft.ML; using System; const string modelPath = "./model.onnx"; MLContext mlContext = new MLContext(); mlContext.Transforms.ApplyOnnxModel(modelPath); Console.WriteLine("HelloWorld!"); Console.ReadLine();
错误信息
在Windows 10上运行时,直接抛出如下异常:
Unhandled exception. System.TypeInitializationException: The type initializer for 'Microsoft.ML.OnnxRuntime.NativeMethods' threw an exception. ---> System.DllNotFoundException: Unable to load DLL 'onnxruntime' or one of its dependencies
项目配置 (.csproj)
为了确保onnxruntime.dll能被正确包含到发布包中,我特意手动添加了Microsoft.ML.OnnxRuntime的包引用(在我的Windows 11电脑上其实不需要这一步),完整的项目配置如下:
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net9.0</TargetFramework> <SelfContained>true</SelfContained> <RuntimeIdentifier>win-x64</RuntimeIdentifier> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.ML" Version="4.0.3" /> <PackageReference Include="Microsoft.ML.OnnxRuntime" Version="1.23.2" /> <PackageReference Include="Microsoft.ML.OnnxTransformer" Version="4.0.3" /> </ItemGroup> </Project>
已尝试的排查动作
- 发布方式:我使用
dotnet publish -c Release生成完整发布包,将整个publish文件夹复制到客户的Windows 10电脑上; - DLL存在性检查:在客户电脑上执行
where onnxruntime.dll,能找到两个文件——一个在exe同级目录,另一个在System32,按加载优先级应该优先使用exe同级的文件; - 依赖项检查:用Dependencies工具扫描exe和onnxruntime.dll,没有发现缺失的依赖DLL。
求助点
明明exe目录下已经存在onnxruntime.dll,且在Windows 11上完全正常,为什么Windows 10会报无法加载的错误?有没有Windows 10特有的依赖项我没考虑到,或者是发布配置需要调整的地方?麻烦各位大佬给点思路,谢谢!




