gpt4 book ai didi

c# - 您可以在 .Net Core 中动态加载跨平台 native /非托管 dll/lib 吗?

转载 作者:太空狗 更新时间:2023-10-29 20:19:19 27 4
gpt4 key购买 nike

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

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

在 Windows 上,我们使用 DllImport to LoadModule 来处理这个问题。然后您可以使用 GetProcAddress 将地址映射到您可以调用的委托(delegate),有效地动态加载 api 调用。

有什么方法可以开箱即用地在 .Net Core 中执行此操作,以便您执行加载的逻辑可以在 Linux、Mac OSX 和 Windows 上跨平台工作?

这是可以 build 的,但我正在尝试在追逐那只兔子之前看看是否有办法做到这一点。

最佳答案

一个潜在的解决方案与 my answer 有关SO 问题 Load unmanaged static dll in load context :

您可以使用 AssemblyLoadContextSystem.Runtime.Loader包。

LoadUnmanagedDll() 的实现包含加载平台相关 native 库的逻辑:

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

runtimes/platform/native/nupkg convention但您可以使用任何您喜欢的路径。

您的 pinvoke 方法将类似于:

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

通过共享接口(interface)调用像 nng_aio_alloc 这样的本地方法将触发 nng 库的加载,你的 LoadUnmanagedDll() 函数将被调用.

关于c# - 您可以在 .Net Core 中动态加载跨平台 native /非托管 dll/lib 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49270527/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com