你能在.Net Core中动态加载跨平台的Native/Unmanaged dll/libs吗?

Rya*_*ann 7 c# asp.net-core-mvc .net-core asp.net-core-1.0 asp.net-core-2.0

在.Net Core中,您可以使用[DllImport]进行PInvoke,

但是如果你想动态加载和映射本机api调用,DllImport并不能解决问题.

在Windows上,我们使用DllImport到LoadModule处理了这个问题.然后,您可以使用GetProcAddress将地址映射到您可以调用的委托,从而有效地动态加载api调用.

有没有办法在.Net Core中开箱即用,这样你的逻辑加载工作就可以在Linux,Mac OSX和Windows上跨平台工作?

这可以建立,但我试图看看有没有办法在追逐那只兔子之前做到这一点.

Jak*_*ake 5

一种可能的解决方案与对SO问题的回答有关:在加载上下文中加载非托管静态dll

您可以在System.Runtime.Loader包中使用AssemblyLoadContext

您的实现LoadUnmanagedDll()包含加载依赖平台的本机库的逻辑:

string arch = Environment.Is64BitProcess ? "-x64" : "-x86";
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
    var fullPath = Path.Combine(assemblyPath, "runtimes", "osx" + arch, "native", "libnng.dylib");
    return LoadUnmanagedDllFromPath(fullPath);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
    var fullPath = Path.Combine(assemblyPath, "runtimes", "linux" + arch, "native", "libnng.so");
    return LoadUnmanagedDllFromPath(fullPath);
}
else // RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
{
    var fullPath = Path.Combine(assemblyPath, "runtimes", "win" + arch, "native", "nng.dll");
    return LoadUnmanagedDllFromPath(fullPath);
}
Run Code Online (Sandbox Code Playgroud)

runtimes/platform/native/nupkg约定,但是您可以使用任何喜欢的路径。

您的pinvoke方法将类似于:

[DllImport("nng", CallingConvention = CallingConvention.Cdecl)]
public static extern int nng_aio_alloc(out nng_aio aio, AioCallback callback, IntPtr arg);
Run Code Online (Sandbox Code Playgroud)

nng_aio_alloc通过共享接口调用本机方法将触发然后加载nng库,并且LoadUnmanagedDll()将调用您的函数。


Rya*_*ann 2

在 .NetCore Repo 上提出问题后,我被告知这将被添加到 .Net Core 中,但不会出现在 2.1 中。

目前,github 上有一个由用户创建的原型实现,位于此处:

https://github.com/mellinoe/nativelibraryloader