Skip to content

Recipe Win Load External DLL

EBenkler edited this page Nov 15, 2020 · 2 revisions

Sometimes you might need to load an external DLL with ctypes that is neither bundled with the executable nor it is a system DLL.

For security reasons in the bootloader we call SetDllDirectory function with our extraction path. This prevents loading a dll from the current directory or any other directory besides sys._MEIPASS and system paths.

Workaround

If SetDllDirectory is called with a Null argument to reset the dll search path then loading a dll from the current directory works. Use the following code snippet in your app:

import ctypes
import os
import sys

if hasattr(sys, '_MEIPASS'): # if _MEIPASS is used by pyinstaller
    # Override dll search path.
    ctypes.windll.kernel32.SetDllDirectoryW(YOUR_PATH_WITH_EXTERNAL_DLL)
    # Init code to load external dll
    ctypes.CDLL('library.dll')
    # ...
    # Restore dll search path.
    ctypes.windll.kernel32.SetDllDirectoryW(sys._MEIPASS)
else: # otherwise, just use LoadLibrary straight ahead
    ctypes.CDLL('library.dll')
    # ...

Links