ctypes是否不释放字符串缓冲区?

问题描述 投票:2回答:1

[我很好奇,无论是使用Windows API HeapAlloc(通过ctypes.WINFUNCTYPE)还是使用ctypes.create_string_buffer分配整数数组的速度都更快,当我取消分配缓冲区时,我发现了一些奇怪的行为。通常,当您创建字符串缓冲区时

import ctypes
buffer = ctypes.create_string_buffer(1024 * 1024 * 1024) # 1 GiB

并稍后删除

del buffer

其内存已释放。您可以通过检查进程的内存使用情况来查看此信息。 但是,如果将缓冲区强制转换为删除前的指针,则该参数>

buffer = ctypes.cast(buffer, ctypes.c_void_p) # also works with POINTER(...) instead of c_void_p
del buffer

缓冲区的内存不再被释放。这很奇怪,因为指针知道缓冲区:

buffer = ctypes.create_string_buffer(1024 * 1024 * 1024) # 1 GiB
ptr = ctypes.cast(buffer, ctypes.c_void_p)

ptr._objects      # -> {<some int> : <ctypes.c_char_Array_5 object at ...>}
buffer2 = list(ptr._objects.values())[0]
buffer2 is buffer # -> True

# Also works with POINTER(...) instead of c_void_p

这是预期的行为吗?在我看来,似乎有人忘记了Py_DECREF(b_objects)PyCSimpleType中的某个地方的PyCPointerType


我正在Windows 10 x64上使用Python 3.7.4 x64

[我很好奇,无论是使用Windows API HeapAlloc(通过ctypes.WINFUNCTYPE)还是使用ctypes.create_string_buffer分配整数数组的速度都更快,当我发现...

python-3.x ctypes
1个回答
3
投票

看起来像是参考泄漏。

© www.soinside.com 2019 - 2024. All rights reserved.