How can I unload a DLL using ctypes in Python?

you should be able to do it by disposing the object

mydll = ctypes.CDLL('...')
del mydll
mydll = ctypes.CDLL('...')

EDIT: Hop’s comment is right, this unbinds the name, but garbage collection doesn’t happen that quickly, in fact I even doubt it even releases the loaded library.

Ctypes doesn’t seem to provide a clean way to release resources, it does only provide a _handle field to the dlopen handle…

So the only way I see, a really, really non-clean way, is to system dependently dlclose the handle, but it is very very unclean, as moreover ctypes keeps internally references to this handle. So unloading takes something of the form:

mydll = ctypes.CDLL('./mylib.so')
handle = mydll._handle
del mydll
while isLoaded('./mylib.so'):
    dlclose(handle)

It’s so unclean that I only checked it works using:

def isLoaded(lib):
   libp = os.path.abspath(lib)
   ret = os.system("lsof -p %d | grep %s > /dev/null" % (os.getpid(), libp))
   return (ret == 0)

def dlclose(handle)
   libdl = ctypes.CDLL("libdl.so")
   libdl.dlclose(handle)

Leave a Comment