如何在 Python 中使用 ctypes 卸载 DLL? [英] How can I unload a DLL using ctypes in Python?

查看:34
本文介绍了如何在 Python 中使用 ctypes 卸载 DLL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ctypes 在 Python 中加载 DLL.这很好用.

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

现在我们希望能够在运行时重新加载该 DLL.

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

直接的方法似乎是:1.卸载DLL2.加载DLL

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

不幸的是,我不确定卸载 DLL 的正确方法是什么.

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

_ctypes.FreeLibrary 可用,但私有.

_ctypes.FreeLibrary is available, but private.

是否有其他方法可以卸载 DLL?

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('...')

Hop 的评论是正确的,这解除了名称的绑定,但垃圾收集不会那么快发生,事实上我什至怀疑它甚至释放了加载的库.

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 似乎没有提供一种干净的方式来释放资源,它只为 dlopen 句柄提供了一个 _handle 字段...

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

所以我看到的唯一方法,一种非常,非常不干净的方法,是系统依赖地关闭句柄,但它非常非常不干净,因为此外,ctypes 保持对这个句柄的内部引用.因此卸载采用以下形式:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆