ctypes.util.find_library does not respect os.add_dll_directory #111104
Description
Bug report
Bug description:
os.add_dll_directory's documentation states that "This search path is used when resolving dependencies for imported extension modules (the module itself is resolved through sys.path), and also by ctypes.", yet paths added there do not affect ctypes.util.find_library (one can easily verify that the implementation of the latter simply walks PATH:
Lines 55 to 68 in b4c215e
| def find_library(name): | |
| if name in ('c', 'm'): | |
| return find_msvcrt() | |
| # See MSDN for the REAL search order. | |
| for directory in os.environ['PATH'].split(os.pathsep): | |
| fname = os.path.join(directory, name) | |
| if os.path.isfile(fname): | |
| return fname | |
| if fname.lower().endswith(".dll"): | |
| continue | |
| fname = fname + ".dll" | |
| if os.path.isfile(fname): | |
| return fname | |
| return None |
I do realize that find_library's doc does state "The purpose of the find_library() function is to locate a library in a way similar to what the compiler or runtime loader does (on platforms with several versions of a shared library the most recent should be loaded), while the ctypes library loaders act like when a program is run, and call the runtime loader directly." which might justify the difference in behavior; still, it would be nice if ctypes provided a function (or changed find_library) to return the path of the library that would be loaded while respecting add_dll_directory (right now a workaround would be to call GetModuleFileNameEx ourselves on the handle returned by WinDLL).
CPython versions tested on:
3.12
Operating systems tested on:
Windows
Metadata
Metadata
Assignees
Labels
Projects
- StatusShow more project fieldsDone
Activity
davidva-ecco commentedon Apr 9, 2025
Did you ever find a solution to this?
Using Python 3.12.6 and Windows 11 64-bit, I am also struggling with
ctypes.util.find_library()not finding DLLs in directories added byos.add_dll_directory(), but will locate them if the full path to the DLL is provided tofind_library(). Unfortunately this breaks an imported module that usesfind_library()with the DLL name to locate a DLL.Test folder structure:
tester.py:
Output of
python tester.py:encukou commentedon Feb 23, 2026
I'm proposing to soft-deprecate
ctypes.util.find_library: https://discuss.python.org/t/106232encukou commentedon Mar 20, 2026
It is now soft-deprecated. It cannot be made to work correctly and consistently on all platforms, and any change runs a chance to break whatever workarounds people already have in place.
I'm prioritizing stability over new features, and encourage solving this outside ctypes itself.