18

我正在加载一个带有 ctypes 的 dll,如下所示:

lib = cdll.LoadLibrary("someDll.dll");

完成库后,我需要将其卸载以释放它使用的资源。我在文档中查找有关如何执行此操作的任何内容时遇到问题。我看到这篇相当老的帖子:如何在 Python 中使用 ctypes 卸载 DLL?. 我希望有一些我没有发现的明显的东西,而不是黑客攻击。

4

1 回答 1

23

我发现的唯一真正有效的方法是负责调用LoadLibraryFreeLibrary。像这样:

import ctypes

# get the module handle and create a ctypes library object
libHandle = ctypes.windll.kernel32.LoadLibraryA('mydll.dll')
lib = ctypes.WinDLL(None, handle=libHandle)

# do stuff with lib in the usual way
lib.Foo(42, 666)

# clean up by removing reference to the ctypes library object
del lib

# unload the DLL
ctypes.windll.kernel32.FreeLibrary(libHandle)

更新:

从 Python 3.8 开始,ctypes.WinDLL()不再接受None表示没有传递文件名。相反,您可以通过传递一个空字符串来解决此问题。

https://bugs.python.org/issue39243

于 2012-10-29T20:31:21.017 回答