tags:

views:

551

answers:

1

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

Edit: 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.

+2  A: 
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
Unknown
Thanks. I'm glad I asked. I didn't expect an answer. :)
Scott
I think I am one of the few ctypes experts here. Strangely I only have written a couple of c/python bindings, and have almost no experience with pyrex/boost/regular modules.
Unknown
Let me ask you this. Can I use ctypes pointers like C pointers? Like traversing an array of chars with an addition or subtraction?
Scott
Nevermind. I just did a search and found what I needed.
Scott
Yes. (The notification seems to be broken). intptr = POINTER(c_int)() intptr[0] intptr[234] etc
Unknown
I'm assuming never do ptr[0:] lol. I tried just to see.
Scott