gpt4 book ai didi

.net-core - 具有 native 库依赖项的 .NET Core 项目

转载 作者:行者123 更新时间:2023-12-03 09:28:07 25 4
gpt4 key购买 nike

我正在使用 [DllImport] 在 .NET Core 中编写依赖 native 代码的应用程序.我有用于 win-x64、win-x86 和 linux-x64 的 native 编译库工件。

我的项目结构是这样的:

MyApp
|--Main.cs
|--runtimes
|--win-x86
|--native
|--somelibrary.dll
|--win-x64
|--native
|--somelibrary.dll
|--linux-x64
|--native
|--libsomelibrary.so

当我运行应用程序时,我得到了 DLL not found 异常。

我尝试使用 MSBuild 目标解决方案 here , 但这只复制了一个 dll在编译时到主输出文件夹。但是,我希望输出在输出文件夹中包含与上述运行时文件夹相同的结构中的所有三个 native 库,并将兼容 native 库的选择留给 .NET Core 运行时主机。

因此,如果用户在 Windows x86 中运行应用程序,它将使用 win-x86,依此类推。

当我引用像 SkiaSharp 这样的原生包装器时,我注意到了来自 NuGet,它实际上会很好地集成到我的应用程序中,并将所有 Assets 包含在运行时文件夹结构中,以便在运行时在多个环境中工作。我怎样才能做到这一点?

编辑:

我最终为本地库绑定(bind)创建了一个 nuget 包,并在我的其他项目中引用了 nuget。

最佳答案

这应该将您的文件夹结构复制到输出文件夹,只需将其放在第一个 </PropertyGroup> 下即可在您的 MyApp.csproj :

<ItemGroup>
<None Update="runtimes\**" CopyToOutputDirectory="PreserveNewest"/>
</ItemGroup>
以防万一,有一种方法可以更好地控制使用 DllImport 加载 native 库的方式。通过 DllImportResolver代表您的大会。
public delegate IntPtr DllImportResolver(string libraryName, Assembly assembly, DllImportSearchPath? searchPath);
还有 NativeLibrary允许为 .net 核心设置和加载 native 库的类。一些示例代码:
static class Sample
{
const string NativeLib = "NativeLib";

static Sample()
{
NativeLibrary.SetDllImportResolver(typeof(Sample).Assembly, ImportResolver);
}

private static IntPtr ImportResolver(string libraryName, Assembly assembly, DllImportSearchPath? searchPath)
{
IntPtr libHandle = IntPtr.Zero;
//you can add here different loading logic
if (libraryName == NativeLib && RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && Environment.Is64BitProcess)
{
NativeLibrary.TryLoad("./runtimes/win-x64/native/somelib.dll", out libHandle);
} else
if (libraryName == NativeLib)
{
NativeLibrary.TryLoad("libsomelibrary.so", assembly, DllImportSearchPath.ApplicationDirectory, out libHandle);
}
return libHandle;
}

[DllImport(NativeLib)]
public static extern int DoSomework();
}

关于.net-core - 具有 native 库依赖项的 .NET Core 项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58955723/

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