如何部署使用C ++ / CLI库的C#库

问题描述 投票:1回答:1

我有一个使用AnyCPU构建的C#库,但它依赖于一些C ++ / CLI库。我已经为x86和x64 Windows编译了C ++ / CLI。看起来我只能将C ++ / CLI库的单个引用添加到C#项目中(否则文件会相互写入)。我认为有可能有一个x86和x64文件夹,相应的库将存在。但是当我尝试这个时,我会得到关于无法找到库的运行时异常。

有没有办法将x86和x64都包含在我的AnyCpu库中,以便在部署时调用应用程序可以决定是否需要x86或x64?

c# .net c++-cli
1个回答
2
投票

基本上你需要做以下事情:

  • 检测进程架构(x86或x64)
  • 根据体系结构加载正确的库

根据流程架构获取要加载的库的路径:

    public NativeLibraryLoader(string path32, string path64)
    {
        if (!File.Exists(path32))
            throw new FileNotFoundException("32-bit library not found.", path32);

        if (!File.Exists(path64))
            throw new FileNotFoundException("64-bit library not found.", path64);

        string path;

        switch (RuntimeInformation.ProcessArchitecture)
        {
            case Architecture.X86:
                path = path32;
                break;
            case Architecture.X64:
                path = path64;
                break;
            default:
                throw new PlatformNotSupportedException();
        }

        ...
    }

使用LoadLibrary加载本机库:

    /// <summary>
    ///     https://msdn.microsoft.com/en-us/library/windows/desktop/ms684175(v=vs.85).aspx
    /// </summary>
    /// <param name="lpLibFileName"></param>
    /// <returns></returns>
    [DllImport("kernel32.dll", EntryPoint = "LoadLibrary", SetLastError = true, CharSet = CharSet.Unicode)]
    public static extern IntPtr LoadLibrary(string lpLibFileName);

完整的例子:

你可以查看aubio.net,我为aubio编写的.NET包装器。这是一个AnyCPU程序集,它将根据运行的当前架构加载x86x64库。

这些是您感兴趣的部分:

https://github.com/aybe/aubio.net/tree/master/Aubio/Interop

https://github.com/aybe/aubio.net/blob/master/Aubio/AubioNative.cs

警告:

此方法说明如何加载本机库而不是托管库。

正如@ Flydog57指出的那样,要加载托管程序集,请使用Assembly.Load

© www.soinside.com 2019 - 2024. All rights reserved.