题
我想调整一个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
>>>
但是,这是难看传递类型,而不是尺寸。它适用于它的目的,就是这样。
解决方案
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
不隶属于 StackOverflow