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

时间:2019-04-04 23:38:40

标签: c# .net c++-cli

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

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

1 个答案:

答案 0 :(得分: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

相关问题