Recipe Win Load External DLL

Martin Zibricky edited this page Nov 29, 2015 · 1 revision

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

# 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)

Links