Search code examples
.net64-bitfusion

32 or 64 bit DLL loading from .Net managed code


I have a unmanaged DLL (the scilexer.dll of Scintilla code editor, used by Scintilla.Net from CodePlex) that is loaded from a managed application trough the Scintilla.Net component. The windows managed application runs without problem on both 32 and 64 bit environments, but I need to create different installations that uses the 64 or the 32 scilexer.dll.

Is there a way to distribute both DLLs in 32 and 64 bit format so that the DLL loader of the .Net framework loads the unmanaged DLL in the 32 or 64 bit format depending on some .config option or some "path name magic" stuff?


Solution

  • P/Invoke uses LoadLibrary to load DLLs, and if there is already a library loaded with a given name, LoadLibrary will return it. So if you can give both versions of the DLL the same name, but put them in different directories, you can do something like this just once before your first call to a function from scilexer.dll, without needing to duplicate your extern declarations:

        string platform = IntPtr.Size == 4 ? "x86" : "x64";
        string dll = installDir + @"\lib-" + platform + @"\scilexer.dll";
        if (LoadLibrary(dll) == IntPtr.Zero)
            throw new IOException("Unable to load " + dll + ".");