Skip to content

Commit e7ec7e2

Browse files
authored
[Windows] Workaround for loading bundled DLLs (#4893) (#5094)
1 parent 95b26e0 commit e7ec7e2

File tree

3 files changed

+30
-8
lines changed

3 files changed

+30
-8
lines changed

torchvision/extension.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
import ctypes
2+
import os
3+
import sys
4+
from warnings import warn
5+
16
import torch
27

38
from ._internally_replaced_utils import _get_extension_path
@@ -62,4 +67,22 @@ def _check_cuda_version():
6267
return _version
6368

6469

70+
def _load_library(lib_name):
71+
lib_path = _get_extension_path(lib_name)
72+
# On Windows Python-3.8+ has `os.add_dll_directory` call,
73+
# which is called from _get_extension_path to configure dll search path
74+
# Condition below adds a workaround for older versions by
75+
# explicitly calling `LoadLibraryExW` with the following flags:
76+
# - LOAD_LIBRARY_SEARCH_DEFAULT_DIRS (0x1000)
77+
# - LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR (0x100)
78+
if os.name == "nt" and sys.version_info < (3, 8):
79+
_kernel32 = ctypes.WinDLL("kernel32.dll", use_last_error=True)
80+
if hasattr(_kernel32, "LoadLibraryExW"):
81+
_kernel32.LoadLibraryExW(lib_path, None, 0x00001100)
82+
else:
83+
warn("LoadLibraryExW is missing in kernel32.dll")
84+
85+
torch.ops.load_library(lib_path)
86+
87+
6588
_check_cuda_version()

torchvision/io/_video_opt.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,11 @@
88
import numpy as np
99
import torch
1010

11-
from .._internally_replaced_utils import _get_extension_path
11+
from ..extension import _load_library
1212

1313

1414
try:
15-
lib_path = _get_extension_path('video_reader')
16-
torch.ops.load_library(lib_path)
15+
_load_library("video_reader")
1716
_HAS_VIDEO_OPT = True
1817
except (ImportError, OSError):
1918
_HAS_VIDEO_OPT = False

torchvision/io/image.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
import torch
22
from enum import Enum
3+
from warnings import warn
34

4-
from .._internally_replaced_utils import _get_extension_path
5+
from ..extension import _load_library
56

67

78
try:
8-
lib_path = _get_extension_path('image')
9-
torch.ops.load_library(lib_path)
10-
except (ImportError, OSError):
11-
pass
9+
_load_library("image")
10+
except (ImportError, OSError) as e:
11+
warn(f"Failed to load image Python extension: {e}")
1212

1313

1414
class ImageReadMode(Enum):

0 commit comments

Comments
 (0)