【发布时间】:2013-03-21 23:56:18
【问题描述】:
我在各种 Python 代码库中看到的在运行时动态生成/加载 C 函数的常见习语是:
import tempfile
import shutil
from ctypes import CDLL
workdir = tempfile.mkdtemp()
try:
# Generate and write code in workdir
# ...
# Compile and link into an .so/.dylib/.dll
# ...
lib = CDLL(path_to_lib)
finally:
shutil.rmtree(workdir)
虽然这似乎在 *nix 系统上运行良好,但我不确定它在 Win32 上的运行情况如何。这是因为,根据我的经验,当临时目录中的 .dll 映射到进程时,无法取消链接。因此,rmtree 将失败。
我可以使用哪些选项来确保在 Win32 上尽快删除 .dll(以及它所在的目录)(以便在底层 lib 被 gc'ed 或应用程序终止时如此以免留下临时的麻烦)。
【问题讨论】: