문제

CTYPES 어레이 크기를 조정하고 싶습니다. 보시다시피, ctypes.resize는 가능한 것처럼 작동하지 않습니다. 배열 크기를 조정하는 기능을 작성할 수 있지만 이에 대한 다른 솔루션을 알고 싶었습니다. 어쩌면 나는 CTYPES 트릭을 놓치거나 단순히 Resize Orde를 사용했을 수도 있습니다. 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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top