【问题标题】:.NET Core linking unmanaged binaries in linux.NET Core 在 linux 中链接非托管二进制文件
【发布时间】:2020-05-07 01:07:49
【问题描述】:

我正在尝试在 ubuntu 上将 libshout 与 C# 一起使用,但无法链接二进制文件。

我将此添加到我的 .csproj 中

<ItemGroup>
    <None Include="libshout.so">
        <Pack>true</Pack>
        <PackagePath>/usr/lib/x86_64-linux-gnu/</PackagePath>
        <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
</ItemGroup>

在我的 C# 代码中,我有:

[DllImport("libshout.so", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
private static extern void shout_init();

我可以看到二进制文件存在

/usr/lib/x86_64-linux-gnu/libshout.so.3.2.0

我收到此错误:

Microsoft.Common.CurrentVersion.targets(4601, 5): [MSB3030] 不能 复制文件 “/home/pc/RiderProjects/icecast-radio-broadcast/Api/libshout.so” 因为没找到。

感谢任何帮助或提示。谢谢

【问题讨论】:

标签: c# linux .net-core native asp.net-core-3.1


【解决方案1】:

您可以使用NativeLibrary 类更改查找libshout.so 的位置。

static class LibshoutInterop
{
    const string Libshout = "libshout";

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

    private static IntPtr ImportResolver(string libraryName, Assembly assembly, DllImportSearchPath? searchPath)
    {
        IntPtr libHandle = IntPtr.Zero;
        if (libraryName == Libshout)
        {
            // Where where this is looked up
            NativeLibrary.TryLoad("/usr/lib/x86_64-linux-gnu/libshout.so", assembly, DllImportSearchPath.System32, out libHandle);
        }
        return libHandle;
    }

    [DllImport(LibShout, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall))]
    public static extern int shout_init();
}

Tom Deseyn 在这里做了更详细的文章:https://developers.redhat.com/blog/2019/09/06/interacting-with-native-libraries-in-net-core-3-0/

【讨论】:

    【解决方案2】:

    它似乎是当你指定。 DllImport("libshout.so" 它查看执行环境的相对路径。您可以尝试将 lib 复制或链接到您的应用运行的目录,或者您可以提供 DllImport 的绝对路径,它也需要具有读取文件的权限。

    【讨论】:

      猜你喜欢
      • 2021-08-26
      • 1970-01-01
      • 1970-01-01
      • 2011-03-13
      • 2018-10-07
      • 2012-09-03
      • 2016-03-04
      • 2015-02-27
      • 2015-03-19
      相关资源
      最近更新 更多