使用ctypes加载DLL后无法删除文件夹目录的问题
问题根源
在Windows系统中,通过ctypes.CDLL加载DLL文件后,系统会锁定该文件以防止被修改或删除。你代码里的del self.dll仅删除了Python层面的对象引用,并未通知系统卸载DLL,因此文件仍处于被占用状态,导致shutil.rmtree执行时触发权限拒绝错误。另外,__del__方法的执行时机由Python垃圾回收机制决定,无法保证在调用del test后立即执行,进一步加剧了资源释放的不确定性。
解决方案
1. 手动调用Windows API卸载DLL
通过Windows的FreeLibrary API手动释放DLL句柄,解锁文件后再执行删除操作:
from ctypes import CDLL, windll import shutil import os class Test: def __init__(self): self.dll = CDLL("C:/DLL/ztrace_maps.dll") self.dll_handle = self.dll._handle # 获取DLL的系统句柄 def cleanup(self): # 调用FreeLibrary卸载DLL windll.kernel32.FreeLibrary(self.dll_handle) del self.dll # 检查目录存在性,避免重复删除报错 if os.path.exists("C:/DLL/"): shutil.rmtree("C:/DLL/") test = Test() test.cleanup()
2. 使用上下文管理器(推荐)
用上下文管理器(with语句)控制资源生命周期,确保DLL被正确卸载后再清理目录,规避__del__的不确定性:
from ctypes import CDLL, windll import shutil import os class Test: def __enter__(self): self.dll = CDLL("C:/DLL/ztrace_maps.dll") self.dll_handle = self.dll._handle return self def __exit__(self, exc_type, exc_val, exc_tb): # 卸载DLL windll.kernel32.FreeLibrary(self.dll_handle) del self.dll # 清理目录 if os.path.exists("C:/DLL/"): shutil.rmtree("C:/DLL/") # 用with语句自动管理资源 with Test() as test: # 在此执行业务逻辑 pass
3. 避免重复删除操作
原代码中del test触发__del__删除目录,之后又手动调用shutil.rmtree,属于重复操作,修正时只需保留一处清理逻辑即可。
内容的提问来源于stack exchange,提问作者programmer_2020
相关产品推荐
相关产品推荐

