pythonpython-3.xdllsearch-pathpyd

How to specify PYD dll dependencies search paths at runtime with python


I created a Python PYD extension module which i can import fine with Python 3.9.1 when i copy all the direct and transitive dll dependencies to the same directory where the PYD file lies.

However, whatever i try, i fail at adding the needed search paths at runtime with the goal of not having to copy all the dependent dlls but let the module loader find them at runtime.

I tried to add them with

at runtime.

I also tried launching the py from a console where i first manually set up the paths with SET "path=%path%;C:\tst" and SET "pythonpath=%pythonpath%;C:\tst"

but Python always throws a "ImportError: DLL load failed while importing TestModule: The specified module could not be found.".

I checked the PATH environment of python.exe process right before the import statement and it seems fine, i.e. contains all the needed search paths.

The only thing i can think of is that python is using LoadLibraryEx with LOAD_WITH_ALTERED_SEARCH_PATH to load the PYD.

Is it possible to define the search paths at runtime? What am i doing wrong?

For completeness sake, here's the code for the different way's i'm trying to add the paths:

sys.path.append(r'C:\tst')
try:
    os.environ["PYTHONPATH"]
    assert(False)
except:
    pass
os.environ["PYTHONPATH"] = r'C:\tst'
os.environ["PATH"] = r'C:\tst' + os.pathsep + os.environ["PATH"]

Solution

  • Ok, apparently it's (since V3.8) very simple:

    os.add_dll_directory:

    Add a path to the DLL search path.

    This search path is used when resolving dependencies for imported extension modules (the module itself is resolved through sys.path), and also by ctypes.