Python ctypes可加载Release版DLL却无法加载Debug版的问题排查
VS2022 Debug版C++ DLL无法被Python ctypes加载(Release版正常)
问题背景
在Visual Studio 2022中开发C++ DLL项目,计划通过Python的ctypes库调用。Release版本的DLL能正常加载,但Debug版本始终提示找不到模块,已确认DLL文件存在且路径完全正确。
报错信息
Traceback (most recent call last): File "c:\...\RECURSIVE_NODES\python\gym_cartpole.py", line 25, in <module> libc = ctypes.cdll.LoadLibrary(dll_path) File "C:\miniconda3\lib\ctypes\__init__.py", line 451, in LoadLibrary return self._dlltype(name) File "C:\miniconda3\lib\ctypes\__init__.py", line 373, in __init__ self._handle = _dlopen(self._name, mode) FileNotFoundError: Could not find module 'c:\...\RECURSIVE_NODES\x64\Debug\RECURSIVE_NODES.dll' (or one of its dependencies). Try using the full path with constructor syntax.
测试代码
from pathlib import Path dll_path = 'c:\...\RECURSIVE_NODES\x64\Debug\RECURSIVE_NODES.dll' sPath = Path(dll_path) print(sPath.is_file()) # Release和Debug版均返回True,说明文件存在且路径有效 libc = ctypes.cdll.LoadLibrary(dll_path)
注:代码中省略号代表无关路径部分,将路径中的"Debug"替换为"Release"时,DLL可正常加载。
解决方案
重点关注报错信息中提示的**"或者其某个依赖项"**,按以下步骤排查解决:
- 打开Visual Studio开发者命令提示符,执行命令:
dumpbin /dependents RECURSIVE_NODES.dll,对比Debug和Release版DLL的依赖项。 - 发现Debug版额外依赖Address Sanitizer相关DLL,且该依赖DLL无法被系统找到(即使Visual Studio调试器也无法定位)。
- 在VS项目中禁用Address Sanitizer选项,重新编译Debug版DLL后,Python可正常加载该DLL。
内容的提问来源于stack exchange,提问作者Yeb02
相关产品推荐
相关产品推荐

