dynamically load 32 bit or 64 bit library

I’m creating a wrapper library for use in multiple projects for fmod studio. This wrapper library is written in c# and compiled using the any cpu target, which means it can execute in 32 bit mode or in 64 bit mode. I’m using SetDllDirectory to set the directory from which to load libraries and loading libraries manually before initializing fmod. The reason for this is that DllImport requires a constant string so the 32 bit and 64 bit dll must be named the same. So I’ve put the 32 bit libraries in ./x86 and the 64 bit libraries in ./x64 (both named fmod.dll and fmodstudio.dll without the 64 postfix).

Unfortunately the 64 bit fmodstudio64.dll requires that the fmod library is named fmod64.dll. A workaround for this is to include the renamed fmod.dll and a copy called fmod64.dll which is not so nice.

Implementation for reference:

class Program
{
    static bool Win32 = Marshal.SizeOf(typeof(IntPtr)) == 4;
    static string DLLPath = Win32 ? @"\x86" : @"\x64";

    static void Main(string[] args)
    {
        Console.WriteLine("{0} bit mode detected", Win32 ? "32" : "64");
        
        string dllDir = String.Concat(Directory.GetCurrentDirectory(), DLLPath);
        NativeMethods.SetDllDirectory(dllDir);

        Load(VERSION.dll);
        Load(STUDIO_VERSION.dll);

        using (var fmod = new FmodProxy())
        {
            fmod.Initialize();

            Console.ReadLine();
        }
    }

    private static void Load(string name)
    {
        Console.WriteLine(name);
        IntPtr ptr = NativeMethods.LoadLibrary(name);
        if (ptr == IntPtr.Zero)
        {
            Console.WriteLine(Marshal.GetLastWin32Error());
        }
        else
        {
            Console.WriteLine(name + " loaded");
        }
    }
}

class NativeMethods
{
    [DllImport("kernel32.dll", SetLastError = true)]
    public static extern bool SetDllDirectory(string lpPathName);

    [DllImport("kernel32", SetLastError = true)]
    public static extern IntPtr LoadLibrary(string lpFileName);
}

Hi Wouter,

We have ship a modified version of the 64-bit DLLs with the same name with the Unity integration. You could download that and pull the binaries out. Alternatively you can binary edit fmodstudio64.dll to change the reference to “fmod64.dll” to “fmod.dll\0\0”, (note the explicit NULL characters to pad out the string).