调整 ctypes 数组的大小

2023-12-01

我想调整 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

调整 ctypes 数组的大小 的相关文章