You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Linux x64下Dart FFI加载带依赖的.so库失败求助

解决Linux下Dart加载.so库时依赖库找不到的问题

以下几种方法可以解决依赖库无法加载的问题:

  • 设置LD_LIBRARY_PATH环境变量
    Linux动态链接器默认不会从当前库所在目录查找依赖,需要将库所在目录添加到LD_LIBRARY_PATH中:

    • 运行程序前临时设置:
      export LD_LIBRARY_PATH=/绝对路径/到/lib/native/lib64:$LD_LIBRARY_PATH
      dart run 你的脚本.dart
      
    • 在Dart代码中提前设置(需在加载库前执行):
      import 'dart:io';
      import 'package:path/path.dart' as path;
      import 'dart:ffi' as ffi;
      
      void main() {
        final libDir = path.join(Directory.current.absolute.path, 'lib', 'native', 'lib64');
        // 更新LD_LIBRARY_PATH
        final currentLdPath = Platform.environment['LD_LIBRARY_PATH'] ?? '';
        if (!currentLdPath.contains(libDir)) {
          Platform.environment['LD_LIBRARY_PATH'] = '$libDir:$currentLdPath';
        }
        // 加载目标库
        final libraryPath = path.join(libDir, 'mylib.so');
        final dylib = ffi.DynamicLibrary.open(libraryPath);
      }
      
  • 编译时指定rpath(若可重新编译mylib.so)
    如果有权限重新编译mylib.so,可以在编译时添加-rpath='$ORIGIN'链接选项,让动态链接器自动从当前库所在目录查找依赖:

    gcc -shared -o mylib.so 你的源码文件.c -Wl,-rpath='$ORIGIN'
    

    $ORIGIN是链接器的特殊变量,代表当前mylib.so所在的目录,无需硬编码路径。

  • 创建系统库目录的符号链接(临时应急方案)
    将依赖库链接到系统默认的库搜索目录(如/usr/lib64),但此方法可能干扰系统其他程序,仅作临时测试用:

    sudo ln -s /绝对路径/到/libsecond.so.0 /usr/lib64/libsecond.so.0
    sudo ldconfig
    

内容的提问来源于stack exchange,提问作者Dan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 03:12:38