[我很好奇,无论是使用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分配整数数组的速度都更快,当我发现...
看起来像是参考泄漏。