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

标签 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);
}

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

Unable to load DLL "ArithmeticOprn.dylib": The specified module or one of its dependencies could not be found.

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

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

你能告诉我我缺少什么吗?提前致谢:)

最佳答案

您正在尝试通过显式 dlopen 来缩短 DllImport 行为 - 即使用 dlopen 指定应该的路径由 DllImport 使用。问题是 DllImport 链接是在调用 dlopen 之前在内部完成到 C# 运行时的。

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/

相关文章:

c# - WCF SSL 负载均衡器。负载均衡器更改 ssl 端口

c# - C#中的位运算。如何将 2 long 转换为 bool 结果?

c# - 实体应该映射到它自己的数据库表吗?

javascript - JS 图片上传失败 OSX 本地主机

swift - 基于 Swift 的应用程序可以在 OS X 10.9/iOS 7 及更低版本上运行吗?

c# - 将非托管 dll 嵌入托管 C# dll

c# - 如何翻译 "var a = collection?.First()?.somePropA ?? new A();"

iphone - 关于使用 Accelerate.framework 的问题

c# - 当通过 C# 调用 C++ DLL 的导出类时,该类的 C 样式字符串成员在一个导出函数中是 OK,但在另一个函数中不是

python - 区分 "fundamental"ctypes 数据类型及其子类?