我想调整一个ctypes数组的大小。正如您所看到的,ctypes.resize不能像它那样工作。我可以编写一个函数来调整数组的大小,但我想知道其他一些解决方案。也许我错过了一些ctypes技巧或者我只是简单地使用了resize错误。名称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
>>>
但是传递类型而不是大小是丑陋的。它的作用就是为了它的目的。
答案 0 :(得分:8)
from ctypes import *
list = (c_int*1)()
def customresize(array, new_size):
resize(array, sizeof(array._type_)*new_size)
return (array._type_*new_size).from_address(addressof(array))
list[0] = 123
list = customresize(list, 5)
>>> list[0]
123
>>> list[4]
0