Loading temporary DLLs in Python on Win32

The common idiom I've seen in various Python code bases for dynamically creating / loading a C function at runtime is:

import tempfile import shutil from ctypes import CDLL workdir = tempfile.mkdtemp() try: # Generate and write code in workdir # ... # Compile and link into an .so/.dylib/.dll # ... lib = CDLL(path_to_lib) finally: shutil.rmtree(workdir) 

While this seems to work very well on * nix systems, I'm not sure how well it will work on Win32. This is due to the fact that, in my experience, when a .dll inside a temporary directory is mapped to a process, it cannot be undone. Consequently, rmtree fails.

What options are available for me to make sure that ASAP is deleted on Win32.dll (and the directory in which it is located) since only the base lib was specified or when the application terminated so as not to leave a temporary jerk about).

+4
source share
1 answer

Use the Kernel32 FreeLibrary function to unlock the DLL and reduce its number of links. You can use GetModuleHandleW to get the handle, but it is already available in the _handle attribute.

Edit: The main _ctypes module already provides this function, as well as dlclose for POSIX. If there is an error, these functions raise a WindowsError / OSError .

 >>> import os >>> from ctypes import * >>> from _ctypes import FreeLibrary >>> lib = CDLL('./lib.dll') >>> hlib = lib._handle >>> del lib >>> FreeLibrary(hlib) >>> os.remove('./lib.dll') >>> os.path.exists('./lib.dll') False 
+2
source

All Articles