调整ctypes数组大小

4 投票
1 回答
4074 浏览
提问于 2025-04-15 11:52

我想要调整一个ctypes数组的大小。你可以看到,ctypes.resize并不像我想的那样好用。我可以写一个函数来调整数组的大小,但我想知道有没有其他的解决办法。也许我错过了什么ctypes的小技巧,或者我根本就没用对resize。名字叫c_long_Array_0的这个东西似乎告诉我,它可能不适合用resize。

>>> 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
>>> 

不过这样传类型而不是大小看起来有点丑。虽然这样做能达到目的,但就是这样。

1 个回答

12

这段内容是关于编程问题的讨论,可能涉及到一些技术细节。大家在这里分享自己的经验和解决方案,帮助彼此理解如何处理特定的编程挑战。

如果你是编程新手,可能会看到一些代码示例和建议,目的是让你更容易理解如何解决类似的问题。每个人都在努力找到最佳的方法来解决他们遇到的困难。

总之,这里是一个互相学习和交流的地方,大家都在分享自己的知识和经验,希望能帮助到其他人。

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

撰写回答