调整ctypes数组的大小 [英] Resize ctypes array

查看:105
本文介绍了调整ctypes数组的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想调整ctypes数组的大小。如您所见,ctypes.resize不能正常工作。我可以编写一个函数来调整数组的大小,但是我想知道其他一些解决方案。也许我缺少一些ctypes技巧,或者我只是错误地使用了resize。

I'd like to resize a ctypes array. As you can see, ctypes.resize doesn't work like it could. I can write a function to resize an array, but I wanted to know some other solutions to this. Maybe I'm missing some ctypes trick or maybe I simply used resize wrong. The name c_long_Array_0 seems to tell me this may not work with 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

编辑:也许可以使用类似的东西:

Maybe go with something like:

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

但这很难通过类型而不是大小。

But that's ugly passing the type instead of the size. It works for its purpose and that's it.

推荐答案

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

这篇关于调整ctypes数组的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆