我试图动态加载一个库(例如 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);
}

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



但是,当我在DllImport中提供完整路径时,该方法调用将起作用,并且可以获得预期的结果。供您引用,请参阅下面的代码段。
[DllImport("path/to/ArithmeticOprn.dylib")]
public static extern double Add(double a, double b);

你能让我知道我在想什么吗?提前致谢 :)

最佳答案

您正在尝试通过显式 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

它运行带有预加载 path/to 路径的单声道解释器,允许它在该位置找到 dylib

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

关于c# - 无法在MacOS中加载动态库(DYLIB),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53446244/

10-10 15:34