正常Python加载.dll模块失败但Anaconda可运行的问题求助
Python ctypes加载DLL的跨环境兼容问题
我尝试用Python的ctypes包导入本地DLL,代码如下:
import ctypes example_dll = ctypes.windll.LoadLibrary(".\\Example.dll")
该DLL依赖另外两个DLL,已放在同一目录下。代码在Anaconda(Python 3.7)环境中可正常运行,但在常规Python 3.10中运行时抛出错误:
FileNotFoundError: Could not find module: '...\Example.dll' (or one of its dependencies) Try using the full path with constructor syntax.
已尝试的排查方案
- 使用DLL完整路径加载,无效
- 通过Dependency Walker、dumpbin确认所有依赖DLL均存在,且DLL与Python 3.10均为64位
- 安装与Anaconda同版本的常规Python 3.7,问题未解决
- 调用
os.add_dll_directory()指定DLL所在完整路径,无效 - 改用
ctypes.CDLL()加载,仍失败
ctypes代码差异对比
对比Anaconda与常规Python的ctypes.__init__.py中CDLL类的winmode相关代码,发现常规Python缺少Anaconda中的一段逻辑:
Anaconda 版本代码
if _os.name == "nt": if winmode is not None: mode = winmode else: import nt mode = nt._LOAD_LIBRARY_SEARCH_DEFAULT_DIRS if '/' in name or '\\' in name: self._name = nt._getfullpathname(self._name) mode |= nt._LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR # PATH is how DLL lookup has always worked in the past # in Python on Windows. IMHO both the above mode flags # are not wanted and cause many serious regressions within # the conda ecosystem on Windows. We should however # propagate any PATH changes that have happened to Python # library and that is not yet implemented. LOAD_WITH_ALTERED_SEARCH_PATH = 0x00000008 mode = LOAD_WITH_ALTERED_SEARCH_PATH
常规Python 3.10 版本代码
if _os.name == "nt": if winmode is not None: mode = winmode else: import nt mode = nt._LOAD_LIBRARY_SEARCH_DEFAULT_DIRS if '/' in name or '\\' in name: self._name = nt._getfullpathname(self._name) mode |= nt._LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR
将Anaconda中缺失的代码添加到常规Python后,运行抛出新错误:
OSError: [WinError 193] %1 is not a valid Win32 application
该错误通常与32/64位不兼容相关,但已确认所有组件均为64位。
疑问:这是否是Python的bug?为何仅Anaconda环境可正常运行?求解决思路。
注:Example.dll的最后两个依赖为专有DLL,已放置在同一目录,调试发现问题出在Example.dll本身。
内容的提问来源于stack exchange,提问作者Siron
相关产品推荐
相关产品推荐

