Skip to content

Commit 048e689

Browse files
committed
Use win32api.GetModuleFileName() in abs_path_for_dynamic_library(). With this, load_dl_windows.py consistently uses win32api. ctypes is no longer needed, which eliminates the potential for confusion due to different types of handles.
1 parent ee6b92e commit 048e689

File tree

1 file changed

+5
-42
lines changed

1 file changed

+5
-42
lines changed

cuda_bindings/cuda/bindings/_path_finder/load_dl_windows.py

Lines changed: 5 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
# Copyright 2025 NVIDIA Corporation. All rights reserved.
22
# SPDX-License-Identifier: LicenseRef-NVIDIA-SOFTWARE-LICENSE
33

4-
import ctypes
5-
import ctypes.wintypes
64
from typing import Optional
75

86
import pywintypes
@@ -36,46 +34,11 @@ def add_dll_directory(dll_abs_path: str) -> None:
3634

3735

3836
def abs_path_for_dynamic_library(libname: str, handle: pywintypes.HANDLE) -> str:
39-
"""Get the absolute path of a loaded dynamic library on Windows.
40-
41-
Args:
42-
handle: The library handle
43-
44-
Returns:
45-
The absolute path to the DLL file
46-
47-
Raises:
48-
OSError: If GetModuleFileNameW fails
49-
RuntimeError: If the required path length is unreasonably long
50-
"""
51-
MAX_ITERATIONS = 10 # Allows for extremely long paths (up to ~266,000 chars)
52-
buf_size = 260 # Start with traditional MAX_PATH
53-
54-
for _ in range(MAX_ITERATIONS):
55-
buf = ctypes.create_unicode_buffer(buf_size)
56-
n_chars = ctypes.windll.kernel32.GetModuleFileNameW(ctypes.wintypes.HMODULE(handle), buf, buf_size)
57-
58-
if n_chars == 0:
59-
raise OSError(
60-
f"GetModuleFileNameW failed ({libname=!r}, {buf_size=}). "
61-
"Long paths may require enabling the "
62-
"Windows 10+ long path registry setting. See: "
63-
"https://docs.python.org/3/using/windows.html#removing-the-max-path-limitation"
64-
)
65-
if n_chars < buf_size - 1:
66-
return buf.value
67-
68-
buf_size *= 2 # Double the buffer size and try again
69-
70-
raise RuntimeError(
71-
f"Failed to retrieve the full path after {MAX_ITERATIONS} attempts "
72-
f"(final buffer size: {buf_size} characters). "
73-
"This may indicate:\n"
74-
" 1. An extremely long path requiring Windows long path support, or\n"
75-
" 2. An invalid or corrupt library handle, or\n"
76-
" 3. An unexpected system error.\n"
77-
"See: https://docs.python.org/3/using/windows.html#removing-the-max-path-limitation"
78-
)
37+
"""Get the absolute path of a loaded dynamic library on Windows."""
38+
try:
39+
return win32api.GetModuleFileName(handle)
40+
except Exception as e:
41+
raise RuntimeError(f"GetModuleFileName failed for {libname!r} (exception type: {type(e)})") from e
7942

8043

8144
def check_if_already_loaded_from_elsewhere(libname: str) -> Optional[LoadedDL]:

0 commit comments

Comments
 (0)