我正在使用ctypes在Python中加载DLL。这很有效。
现在我们希望能够在运行时重新加载该DLL。
直截了当的做法似乎是: 1.卸载DLL 2.加载DLL
不幸的是我不确定卸载DLL的正确方法是什么。
_ctypes.FreeLibrary可用,但是私有。
还有其他方法可以卸载DLL吗?
答案 0 :(得分:15)
你应该能够通过处置对象
来做到这一点mydll = ctypes.CDLL('...')
del mydll
mydll = ctypes.CDLL('...')
编辑: Hop的评论是正确的,这取消了绑定名称,但垃圾收集不会很快发生,事实上我甚至怀疑它甚至会释放加载的库。
Ctypes似乎没有提供一种释放资源的简洁方法,它只为dlopen句柄提供了一个_handle
字段......
所以我看到的唯一方法,一个真正的,真正非干净的方式,是系统依赖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)
答案 1 :(得分:4)
如果您正在使用iPython或类似的工作流程,则可以卸载DLL以便重建DLL而无需重新启动会话。在Windows中工作我只尝试使用与Windows DLL相关的方法。
REBUILD = True
if REBUILD:
from subprocess import call
call('g++ -c -DBUILDING_EXAMPLE_DLL test.cpp')
call('g++ -shared -o test.dll test.o -Wl,--out-implib,test.a')
import ctypes
import numpy
# Simplest way to load the DLL
mydll = ctypes.cdll.LoadLibrary('test.dll')
# Call a function in the DLL
print mydll.test(10)
# Unload the DLL so that it can be rebuilt
libHandle = mydll._handle
del mydll
ctypes.windll.kernel32.FreeLibrary(libHandle)
我不太了解内部因素,所以我不确定这是多么干净。我认为删除mydll释放Python资源,FreeLibrary调用告诉windows释放它。我曾假设首先释放FreeLibary会产生问题所以我保存了一个库句柄的副本并按照示例中显示的顺序释放它。
我将此方法基于ctypes unload dll,它在前面明确加载了句柄。然而,加载约定并不像简单的" ctypes.cdll.LoadLibrary(' test.dll')"那样干净利落。所以我选择了显示的方法。
答案 2 :(得分:1)
如果您需要此功能,可以编写2个dll,其中dll_A从dll_B加载/卸载库。对于dll_B中的函数,使用dll_A作为python接口加载器和passthrough。
答案 3 :(得分:1)
Piotr's answer帮助了我,但在64位Windows上确实遇到了一个问题:
Traceback (most recent call last):
...
ctypes.ArgumentError: argument 1: <class 'OverflowError'>: int too long to convert
按照this answer中的建议调整FreeLibrary
调用的参数类型可以解决此问题。
因此,我们得出以下完整的解决方案:
import ctypes, ctypes.windll
def free_library(handle):
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
kernel32.FreeLibrary.argtypes = [ctypes.wintypes.HMODULE]
kernel32.FreeLibrary(handle)
用法:
lib = ctypes.CDLL("foobar.dll")
free_library(lib._handle)
答案 4 :(得分:0)
这里是类似讨论的概述(我从中构造了这个答案)。
这是针对Windows和Linux的,因此有2个脚本可供编译。 经过测试:
cpp_code.cpp
extern "C" int my_fct(int n)
{
int factor = 10;
return factor * n;
}
compile-linux.sh
#!/bin/bash
g++ cpp_code.cpp -shared -o myso.so
compile-windows.cmd
set gpp="C:\Program Files\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\bin\g++.exe"
%gpp% cpp_code.cpp -shared -o mydll.dll
PAUSE
Python代码
from sys import platform
import ctypes
if platform == "linux" or platform == "linux2":
# https://stackoverflow.com/a/50986803/7128154
# https://stackoverflow.com/a/52223168/7128154
dlclose_func = ctypes.cdll.LoadLibrary('').dlclose
dlclose_func.argtypes = [ctypes.c_void_p]
fn_lib = './myso.so'
ctypes_lib = ctypes.cdll.LoadLibrary(fn_lib)
handle = ctypes_lib._handle
valIn = 42
valOut = ctypes_lib.my_fct(valIn)
print(valIn, valOut)
del ctypes_lib
dlclose_func(handle)
elif platform == "win32": # Windows
# https://stackoverflow.com/a/13129176/7128154
# https://stackoverflow.com/questions/359498/how-can-i-unload-a-dll-using-ctypes-in-python
lib = ctypes.WinDLL('./mydll.dll')
libHandle = lib._handle
# do stuff with lib in the usual way
valIn = 42
valOut = lib.my_fct(valIn)
print(valIn, valOut)
del lib
ctypes.windll.kernel32.FreeLibrary(libHandle)
如果共享库具有dependencies
,则不必再使用了(但可以-取决于依赖项^^)。我没有仔细研究细节,但是看起来机制如下:库和依赖项已加载。由于未卸载依赖项,因此无法卸载该库。
我发现,如果我在共享库中包含OpenCv
(4.2版),则会使卸载过程混乱。以下示例仅在linux系统上进行了测试:
code.cpp
#include <opencv2/core/core.hpp>
#include <iostream>
extern "C" int my_fct(int n)
{
cv::Mat1b mat = cv::Mat1b(10,8,(unsigned char) 1 ); // change 1 to test unloading
return mat(0,1) * n;
}
编译为
g++ code.cpp -shared -fPIC -Wall -std=c++17 -I/usr/include/opencv4 -lopencv_core -o so_opencv.so
Python代码
from sys import platform
import ctypes
class CtypesLib:
def __init__(self, fp_lib, dependencies=[]):
self._dependencies = [CtypesLib(fp_dep) for fp_dep in dependencies]
if platform == "linux" or platform == "linux2": # Linux
self._dlclose_func = ctypes.cdll.LoadLibrary('').dlclose
self._dlclose_func.argtypes = [ctypes.c_void_p]
self._ctypes_lib = ctypes.cdll.LoadLibrary(fp_lib)
elif platform == "win32": # Windows
self._ctypes_lib = ctypes.WinDLL(fp_lib)
self._handle = self._ctypes_lib._handle
def __getattr__(self, attr):
return self._ctypes_lib.__getattr__(attr)
def __del__(self):
for dep in self._dependencies:
del dep
del self._ctypes_lib
if platform == "linux" or platform == "linux2": # Linux
self._dlclose_func(self._handle)
elif platform == "win32": # Windows
ctypes.windll.kernel32.FreeLibrary(self._handle)
fp_lib = './so_opencv.so'
ctypes_lib = CtypesLib(fp_lib, ['/usr/lib64/libopencv_core.so'])
valIn = 1
ctypes_lib.my_fct.argtypes = [ctypes.c_int]
ctypes_lib.my_fct.restype = ctypes.c_int
valOut = ctypes_lib.my_fct(valIn)
print(valIn, valOut)
del ctypes_lib
当到目前为止的代码示例或说明有任何问题时,请告诉我。另外,如果您知道更好的方法!如果我们能够一劳永逸地解决这个问题,那就太好了。
答案 5 :(得分:0)
为了全面的交叉兼容性:我为每个平台维护了一个各种 dlclose()
等价物的列表,以及从哪个库中获取它们。这是一个有点长的列表,但您可以随意复制/粘贴它。
import sys
import ctypes
import platform
OS = platform.system()
if OS == "Windows": # pragma: Windows
dll_close = ctypes.windll.kernel32.FreeLibrary
elif OS == "Darwin":
try:
try:
# macOS 11 (Big Sur). Possibly also later macOS 10s.
stdlib = ctypes.CDLL("libc.dylib")
except OSError:
stdlib = ctypes.CDLL("libSystem")
except OSError:
# Older macOSs. Not only is the name inconsistent but it's
# not even in PATH.
stdlib = ctypes.CDLL("/usr/lib/system/libsystem_c.dylib")
dll_close = stdlib.dlclose
elif OS == "Linux":
try:
stdlib = ctypes.CDLL("")
except OSError:
# Alpine Linux.
stdlib = ctypes.CDLL("libc.so")
dll_close = stdlib.dlclose
elif sys.platform == "msys":
# msys can also use `ctypes.CDLL("kernel32.dll").FreeLibrary()`. Not sure
# if or what the difference is.
stdlib = ctypes.CDLL("msys-2.0.dll")
dll_close = stdlib.dlclose
elif sys.platform == "cygwin":
stdlib = ctypes.CDLL("cygwin1.dll")
dll_close = stdlib.dlclose
elif OS == "FreeBSD":
# FreeBSD uses `/usr/lib/libc.so.7` where `7` is another version number.
# It is not in PATH but using its name instead of its path is somehow the
# only way to open it. The name must include the .so.7 suffix.
stdlib = ctypes.CDLL("libc.so.7")
dll_close = stdlib.close
else:
raise NotImplementedError("Unknown platform.")
dll_close.argtypes = [ctypes.c_void_p]
然后您可以使用 dll_close(dll._handle)
卸载库 dll = ctypes.CDLL("your-library")
。
此列表取自this file。每次遇到新平台我都会更新the master branch。