简体   繁体   中英

How to deploy a C# library that uses C++/CLI libraries

I have a C# library that builds using AnyCPU but has dependencies on a few C++/CLI libraries. I have compiled the C++/CLI for both x86 and x64 Windows. It seems like I am only able to add a single reference of the C++/CLI library to the C# project (otherwise the files over write each other). I thought it would be possible to have a x86 and x64 folder that the respective libraries would live in. But when I tried this I would get runtime exceptions about not being able to find the library.

Is there any way to include both the x86 and x64 with my AnyCpu library so that when it is deployed the calling application can decide if they want x86 or x64?

Basically you need to do the following:

  • detect process architecture (x86 or x64)
  • load the right library according the architecture

Get the path of the library to load according process architecture:

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

        ...
    }

Load the native library with 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);

Complete example:

You can check out aubio.net , a .NET wrapper I've written for aubio . It's an AnyCPU assembly that will load either the x86 or the x64 library according the current architecture it is running on.

These are the bits you'll be interested by:

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

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

Caveat:

This method explains how to load a native library and not a managed one.

As @Flydog57 pointed out, to load a managed assembly use Assembly.Load instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM