Load native libraries from a dynamic location

 
 
  • Gérald Barré

Today, I had to deal with an uncommon need. In short, the idea is to download a native library (DLL) into a temporary directory (not in the application folder), and use its methods. The content of the DLL is known, so I want to use the DllImport attribute to easily call the methods of the DLL.

The application must work on Windows 10, so I can use a function introduced in Windows 8 AddDllDirectory. This function allows to indicate the paths where the native libraries are. So, you can download the DLL and use the AddDllDirectory function to add its path for DLL loading.

C#
const uint LOAD_LIBRARY_SEARCH_DEFAULT_DIRS = 0x00001000;

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool SetDefaultDllDirectories(uint DirectoryFlags);

[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern int AddDllDirectory(string NewDirectory);

void Initialize()
{
    var downloadDirectory = "temp";
    DownloadDll(downloadDirectory);

    // Indicate to search libraries in
    // - application directory
    // - paths set using AddDllDirectory or SetDllDirectory
    // - %windows%\system32
    SetDefaultDllDirectories(LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);

    // Add the directory of the native dll
    AddDllDirectory(downloadDirectory);

    // Use the native dll
    MyMethod();
}

[DllImport("mydll.dll")]
public static extern int MyMethod();

More information about the kernel32 methods:

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub