0

I have a problem with very simple code.

from ctypes import CDLL
import shutil

# The random library ztrace_maps.dll copied from C:\Windows\SysWOW64 to C:/DLL/

class Test:
    def __init__(self):
        self.dll = CDLL("C:/DLL/ztrace_maps.dll")
    def __del__(self):
        del self.dll
        shutil.rmtree("C:/DLL/")

test = Test()
del test
shutil.rmtree("C:/DLL/")

I am not able to remove the catalog with dll during the execution of the Python script. The Python console (in Pycharm) is working fine. I found a workaround with the execution separate Python script after the closing of the script but should be another possibility to clean resources.

Error:

Traceback (most recent call last):
  File "C:/test.py", line 14, in <module>
    shutil.rmtree("C:/DLL/")
  File "C:\python32\python-3.8.10\Lib\shutil.py", line 740, in rmtree
    return _rmtree_unsafe(path, onerror)
  File "C:\python32\python-3.8.10\Lib\shutil.py", line 618, in _rmtree_unsafe
    onerror(os.unlink, fullname, sys.exc_info())
  File "C:\python32\python-3.8.10\Lib\shutil.py", line 616, in _rmtree_unsafe
    os.unlink(fullname)
PermissionError: [WinError 5] Access is denied: 'C:/DLL/ztrace_maps.dll'
Exception ignored in: <function Test.__del__ at 0x02F55EC8>
Traceback (most recent call last):
  File "C:/test.py", line 10, in __del__
  File "C:\python32\python-3.8.10\Lib\shutil.py", line 740, in rmtree
  File "C:\python32\python-3.8.10\Lib\shutil.py", line 618, in _rmtree_unsafe
  File "C:\python32\python-3.8.10\Lib\shutil.py", line 616, in _rmtree_unsafe
PermissionError: [WinError 5] Access is denied: 'C:/DLL/ztrace_maps.dll'

Process finished with exit code 1

I tested the other commands but with the same result.

  • Any code using `__del__` is not very simple at all. You shouldn't trust `__del__` to be called immediately; if you have resources that need to be immediately released, use the context manager protocol. [There is no guarantee that the DLL `_handle` gets closed, either.](https://github.com/python/cpython/blob/0d04b8d9e1953d2311f78b772f21c9e07fbcbb6d/Lib/ctypes/__init__.py#L376-L379) – AKX Sep 07 '22 at 08:38

2 Answers2

0

DLL files aren't unloaded instantly when deleted, (or maybe not unloaded ever), so deleting the reference to the library doesn't help.

instead you should look into how to unload a DLL (which is somewhat platform dependent) as found in this link.

Ahmed AEK
  • 8,584
  • 2
  • 7
  • 23
0

Thank you Ahmed AEK! The solution with FreeLibrary is working correctly.

from ctypes import CDLL
import shutil
import ctypes

# random library ztrace_maps.dll from C:\Windows\SysWOW64
# copied to C:/DLL/

class Test:
    def __init__(self):
        self.dll = CDLL("C:/DLL/ztrace_maps.dll")
        self._handle = self.dll._handle

    def __del__(self):
        ctypes.windll.kernel32.FreeLibrary(self._handle)
        shutil.rmtree("C:/DLL/")

test = Test()
del test