您需要关闭 DLL 的句柄,以便首先释放它,以便您可以使用该文件,您需要获取库的句柄,然后将其传递给FreeLibrary
Windows,然后您可以使用 DLL 文件执行您需要的操作:
from ctypes import *
file = CDLL('file.dll')
# do stuff here
handle = file._handle # obtain the DLL handle
windll.kernel32.FreeLibrary(handle)
预览:
这是一个测试DLL:
#include <windows.h>
#include <stdio.h>
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) {
switch( fdwReason ) {
case DLL_PROCESS_ATTACH:
puts("DLL loaded");
break;
case DLL_PROCESS_DETACH:
puts("DLL unloaded");
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
}
return TRUE;
}
__declspec(dllexport) void function(void) {
puts("Hello");
}
预览:
>>> from ctypes import *
>>>
>>> file = CDLL('file.dll')
DLL loaded
>>>
>>> # now it's locked
...
>>> file.function()
Hello
0
>>> windll.kernel32.FreeLibrary(file._handle)
DLL unloaded
1
>>> # not it's unlocked
在 Linux 上,您使用dlclose
它将是:
from ctypes import *
file = CDLL('./file.so')
# do stuff here
handle = file._handle # obtain the SO handle
cdll.LoadLibrary('libdl.so').dlclose(handle)
这是一个类似的共享对象:
#include <stdio.h>
__attribute__((constructor)) void dlentry(void) {
puts("SO loaded");
}
void function(void) {
puts("Hello");
}
__attribute__((destructor)) void dlexit(void) {
puts("SO unloaded");
}
预览:
>>> from ctypes import *
>>>
>>> file = CDLL('./file.so')
SO loaded
>>>
>>> file.function()
Hello
6
>>> cdll.LoadLibrary('libdl.so').dlclose(file._handle)
SO unloaded
0
>>>