Skip to content

Commit 1cf5abe

Browse files
authored
gh-145307: Defer loading psapi.dll until ctypes.util.dllist() is called. (GH-145308)
1 parent 201d251 commit 1cf5abe

File tree

2 files changed

+18
-10
lines changed

2 files changed

+18
-10
lines changed

Lib/ctypes/util.py

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -85,24 +85,30 @@ def find_library(name):
8585
wintypes.DWORD,
8686
)
8787

88-
_psapi = ctypes.WinDLL('psapi', use_last_error=True)
89-
_enum_process_modules = _psapi["EnumProcessModules"]
90-
_enum_process_modules.restype = wintypes.BOOL
91-
_enum_process_modules.argtypes = (
92-
wintypes.HANDLE,
93-
ctypes.POINTER(wintypes.HMODULE),
94-
wintypes.DWORD,
95-
wintypes.LPDWORD,
96-
)
88+
# gh-145307: We defer loading psapi.dll until _get_module_handles is called.
89+
# Loading additional DLLs at startup for functionality that may never be
90+
# used is wasteful.
91+
_enum_process_modules = None
9792

9893
def _get_module_filename(module: wintypes.HMODULE):
9994
name = (wintypes.WCHAR * 32767)() # UNICODE_STRING_MAX_CHARS
10095
if _k32_get_module_file_name(module, name, len(name)):
10196
return name.value
10297
return None
10398

104-
10599
def _get_module_handles():
100+
global _enum_process_modules
101+
if _enum_process_modules is None:
102+
_psapi = ctypes.WinDLL('psapi', use_last_error=True)
103+
_enum_process_modules = _psapi["EnumProcessModules"]
104+
_enum_process_modules.restype = wintypes.BOOL
105+
_enum_process_modules.argtypes = (
106+
wintypes.HANDLE,
107+
ctypes.POINTER(wintypes.HMODULE),
108+
wintypes.DWORD,
109+
wintypes.LPDWORD,
110+
)
111+
106112
process = _get_current_process()
107113
space_needed = wintypes.DWORD()
108114
n = 1024
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Defers loading of the ``psapi.dll`` module until it is used by
2+
:func:`ctypes.util.dllist`.

0 commit comments

Comments
 (0)