使用flutter_rust_bridge构建MacOS应用时遇动态库加载失败错误
解决Flutter Rust Bridge macOS动态库加载失败问题
错误原因
你的动态库myapp.dylib的**安装路径(install name)**被设置为全局路径/usr/local/lib/myapp.dylib,导致系统启动App时会去全局目录查找,而非App包内的Contents/Frameworks目录。
修复步骤
1. 修改Rust库的安装路径配置
在你的Rust项目中,通过Cargo配置让编译出的动态库使用@rpath作为路径前缀:
- 方法一:在
Cargo.toml中添加:
[package.metadata.cargo-macos] install-name = "@rpath/myapp.dylib"
- 方法二:在项目根目录的
.cargo/config.toml(无则新建)中添加:
[target.x86_64-apple-darwin] rustflags = ["-C", "link-arg=-install_name", "-C", "link-arg=@rpath/myapp.dylib"] [target.aarch64-apple-darwin] rustflags = ["-C", "link-arg=-install_name", "-C", "link-arg=@rpath/myapp.dylib"]
重新编译Rust库,确保新的install name生效。
2. 配置Xcode嵌入动态库并设置rpath
打开macos/Runner.xcodeproj,选中Runner target:
- 进入Build Settings,找到
Runpath Search Paths,确保包含@executable_path/../Frameworks(默认通常已添加,若缺失则手动加入)。 - 进入Build Phases:
- 点击
+->New Copy Files Phase,将目标目录设为Frameworks,把编译好的myapp.dylib添加到该阶段。 - 或直接在
Embed Frameworks阶段添加myapp.dylib,设置Destination为Frameworks,Code Signing选择Embed & Sign。
- 点击
3. 验证动态库路径
编译后用otool命令检查App引用的库路径是否正确:
otool -L /Users/jp/Documents/Projects/****/build/macos/Build/Products/Debug/myapp.app/Contents/MacOS/myapp
输出中应显示@rpath/myapp.dylib,而非原全局路径。
内容的提问来源于stack exchange,提问作者Jean-Paul Abi-Ghosn
相关产品推荐
相关产品推荐

