This solution is based on idea found on: http://scottbilas.com/blog/automatically-choose-32-or-64-bit-mixed-mode-dlls/
You can check working solution in .\source\LZ4.MixedModeAutoLoad

Let's say I'd like to use LZ4mm.dll, I'm developing on 64-bit platform but I would like to run application on any platform (x86 or x64).

The recipe to load correct assemblies into AnyCPU processor:
  • find out which platform you are running against when running AnyCPU on your development machine (x86 or x64)
  • reference the .dll which matches you development environment (the LZ4mm.dll from \release\x86 or \release\x64)
  • include AutoLoad3264 class in your main executable (source below)
  • put AutoLoad3264.Register("LZ4mm"); in your Main() method

On release:
  • delete LZ4mm.dll from release folder
  • copy LZ4mm.x86.dll and LZ4mm.x64.dll from .\release\any to your release folder
  • done!

How it works?
Because we deleted LZ4mm.dll application cannot find it when it's needed. It raises AssemblyResolve event in such cases and we are handling it by loading LZ4mm.x86.dll or LZ4mm.x64.dll accordingly to current platform.

public static class AutoLoad3264
{
    // http://scottbilas.com/blog/automatically-choose-32-or-64-bit-mixed-mode-dlls/
    public static void Register(string assemblyName, string executableFolder = null)
    {
        if (executableFolder == null)
        {
            var assembly = 
                Assembly.GetEntryAssembly() 
                ?? typeof(AutoLoad3264).Assembly;
            var fileName = assembly.Location;
            executableFolder = Path.GetDirectoryName(fileName);
        }

        AppDomain.CurrentDomain.AssemblyResolve += (_, e) => {
            var n = new AssemblyName(e.Name);
            if (string.Compare(assemblyName, n.Name, true) == 0)
            {
                var platform = (IntPtr.Size == 4) ? "x86" : "x64";
                var fileName = Path.Combine(
                    executableFolder,
                    string.Format("{0}.{1}.dll", assemblyName, platform));
                return Assembly.LoadFile(fileName);
            }
            return null;
        };
    }
}

static void Main(string[] args)
{
    AutoLoad3264.Register("LZ4mm");
    // ... the rest of your application ...
}

Last edited May 5, 2013 at 8:34 PM by Krashan, version 13

Comments

No comments yet.