我想调整一个 ctypes 数组的大小。如您所见, ctypes.resize 无法正常工作。我可以编写一个函数来调整数组的大小,但我想知道一些其他的解决方案。也许我错过了一些 ctypes 技巧,或者我只是使用了错误的调整大小。名称 c_long_Array_0 似乎告诉我这可能不适用于调整大小。
>>> from ctypes import *
>>> c_int * 0
<class '__main__.c_long_Array_0'>
>>> intType = c_int * 0
>>> foo = intType()
>>> foo
<__main__.c_long_Array_0 object at 0xb7ed9e84>
>>> foo[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: invalid index
>>> resize(foo, sizeof(c_int * 1))
>>> foo[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: invalid index
>>> foo
<__main__.c_long_Array_0 object at 0xb7ed9e84>
>>> sizeof(c_int * 0)
0
>>> sizeof(c_int * 1)
4
编辑:也许可以使用类似的东西:
>>> ctypes_resize = resize
>>> def resize(arr, type):
... tmp = type()
... for i in range(len(arr)):
... tmp[i] = arr[i]
... return tmp
...
...
>>> listType = c_int * 0
>>> list = listType()
>>> list = resize(list, c_int * 1)
>>> list[0]
0
>>>
但这很难传递类型而不是大小。它为它的目的而工作,就是这样。