tags:

views:

1405

answers:

1

I'm using ctypes to load a DLL in Python. This works great.

Now we'd like to be able to reload that DLL at runtime.

The straightforward approach would seem to be: 1. Unload DLL 2. Load DLL

Unfortunately I'm not sure what the correct way to unload the DLL is.

_ctypes.FreeLibrary is available, but private.

Is there some other way to unload the DLL?

+3  A: 

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)
Piotr Lesnicki
i don't know, but i doubt that this unloads the dll. i'd guess it only removes the binding from the name in the current namespace (as per language reference)
hop