使用FastText.NetWrapper时出现System.DllNotFoundException求助
问题重现
运行FastText.NetWrapper代码时抛出System.DllNotFoundException,错误信息显示无法找到fasttext.dylib:
Unhandled exception. System.DllNotFoundException: Unable to load shared library 'fasttext' or one of its dependencies. In order to help diagnose loading problems, consider setting the DYLD_PRINT_LIBRARIES environment variable:
dlopen(/Users/a/Desktop/Spell Corrector/MyMLNetProject/bin/Debug/net7.0/runtimes/osx-arm64/native/fasttext.dylib, 0x0001):
tried:
'/Users/a/Desktop/Spell Corrector/MyMLNetProject/bin/Debug/net7.0/runtimes/osx-arm64/native/fasttext.dylib' (no such file),
'/System/Volumes/Preboot/Cryptexes/OS/Users/a/Desktop/Spell Corrector/MyMLNetProject/bin/Debug/net7.0/runtimes/osx-arm64/native/fasttext.dylib' (no such file),
'/Users/a/Desktop/Spell Corrector/MyMLNetProject/bin/Debug/net7.0/runtimes/osx-arm64/native/fasttext.dylib' (no such file)
使用的测试代码:
using FastText.NetWrapper; using System; class Program { static void Main(string[] args) { using (var classifier = new FastTextWrapper()) { classifier.Supervised("train.txt", "model"); string testText = "Bu bir test metnidir."; var result = classifier.PredictSingle(testText); Console.WriteLine($"Tahmin edilen sınıf: {result.Label}"); Console.WriteLine($"Tahmin edilen olasılık: {result.Probability}"); } } }
解决方案
1. 升级并验证NuGet包支持
部分旧版本的FastText.NetWrapper未提供OSX ARM64架构的原生库,先升级到最新版本的NuGet包,然后清理项目的bin和obj目录,重新构建项目。
2. 手动添加适配的fasttext.dylib
如果升级NuGet包后问题仍存在,需要手动获取或编译OSX ARM64版本的动态库:
- 从fasttext官方仓库编译ARM64版本:
git clone https://github.com/facebookresearch/fastText.git cd fastText make # 编译后生成可执行文件,可转成适配的dylib,或直接获取第三方预编译的osx-arm64版本fasttext.dylib - 在项目根目录创建
runtimes/osx-arm64/native文件夹,将fasttext.dylib放入其中。 - 在IDE中选中该文件,设置复制到输出目录为「始终复制」,确保构建时文件被复制到正确的输出路径。
3. 指定项目运行时标识符
在项目的.csproj文件中添加运行时配置,确保项目针对OSX ARM64构建:
<PropertyGroup> <RuntimeIdentifier>osx-arm64</RuntimeIdentifier> </PropertyGroup>
或者通过命令行构建时指定:
dotnet build -r osx-arm64
4. 检查动态库依赖
使用otool命令检查fasttext.dylib的依赖项,确保所有系统依赖都存在:
otool -L fasttext.dylib
如果缺少依赖(如libstdc++.6.dylib),可通过Homebrew安装对应库:
brew install libstdc++
内容的提问来源于stack exchange,提问作者alperenaydin

