如何在Python中使用ctypes卸载DLL? [英] How can I unload a DLL using ctypes in Python?
问题描述
现在我们想要在运行时重新加载该DLL。
直接的方法似乎是:
1.卸载DLL
2.加载DLL
不幸的是,我不知道卸载DLL的正确方法是什么。
_ctypes.FreeLibrary是可用的,但是是私有的。
有没有其他的方式卸载DLL?
你应该能够做它通过处理对象
mydll = ctypes.CDLL('...')
del mydll
mydll = ctypes.CDLL('...')
编辑: Hop的评论是对的,这解开了这个名字,但垃圾收集并不会很快发生,实际上我甚至怀疑它甚至释放了加载的库。
Ctypes似乎没有提供一种干净的方式来释放资源,它只提供一个 _handle
字段dlopen手柄...
所以唯一的方法,我看到,一个真正的真正的非干净的方式是系统依赖dlclose处理,但它非常非常不洁净,因为ctypes内部引用这个句柄。所以卸载需要一些形式:
mydll = ctypes.CDLL('./ mylib.so')
handle = mydll._handle
del mydll
while isLoaded('./ mylib.so'):
dlclose(handle)
这是非常不洁净的,我只检查它的工作原理:
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)
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?
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)
这篇关于如何在Python中使用ctypes卸载DLL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!