无法在 MacOS 中加载动态库 (DYLIB)

Ram*_*mar 5 c# macos dllimport dylib dlopen

我正在尝试动态加载一个库(比如ArithmeticOprn.dylib)并调用该库中提供的方法。请参考下面的示例代码片段,

[DllImport("libdl.dylib")]
public static extern IntPtr dlopen(String fileName, int flags);

[DllImport("ArithmeticOprn.dylib")]
public static extern double Add(double a, double b);

static void Main(string[] args)
{
    dlopen("path/to/ArithmeticOprn.dylib", 2);
    double result = Add(1, 2);
}
Run Code Online (Sandbox Code Playgroud)

在 MacOS 中运行上述示例时,出现以下异常:

无法加载 DLL“ArithmeticOprn.dylib”:找不到指定的模块或其依赖项之一。

但是,当我在 DllImport 中提供完整路径时,方法调用有效,我可以获得预期的结果。供您参考,请参阅下面的代码片段。

[DllImport("path/to/ArithmeticOprn.dylib")]
public static extern double Add(double a, double b);
Run Code Online (Sandbox Code Playgroud)

你能告诉我我错过了什么吗?提前致谢 :)

Pet*_*esh 0

DllImport您试图通过显式来简化行为dlopen- 即使用dlopen来指定 . 应该使用的路径DllImport。问题在于DllImport链接是在C#调用之前在运行时内部完成的dlopen

他们dlopen永远不会进去看看。

为了在DllImport 没有路径的情况下使用,您需要依赖默认搜索行为,即由环境变量$LD_LIBRARY_PATH$DYLD_LIBRARY_PATH当前工作目录指定的位置$DYLD_FALLBACK_LIBRARY_PATH

因此,例如:

env DYLD_LIBRARY_PATH=path/to/ mono test.exe
Run Code Online (Sandbox Code Playgroud)

它使用预加载的路径运行单声道解释器,使其能够在该位置path/to找到。dylib

其他解决方案包括将库移动到可执行文件所在的目录中,在当前工作目录中创建指向库的符号链接。