我正在尝试动态加载一个库(例如 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/