pythonarrayspyobject

the attribute of ctypes.py_object


I am trying to creating a python array and have problems with the following code

def __init__(self, size):
    assert size>0, "Array size must be > 0"
    self._size = size
    # Create the array structure using the ctypes module.

    arraytype = ctypes.py_object * size
    self._elements = arraytype()

In the initialization, it uses ctypes to create an array and I don't really understand the last two lines. I tried to change them into one line

self._elements = ctypes.py_object() * size

But it doesn't work and gives me the error

TypeError: unsupported operand type(s) for *: 'py_object' and 'int'

Could anyone explain it for me?


Solution

  • What you want to do is take the ctypes.py_object * size type first, and then instantiate it:

    self._elements = (ctypes.py_object * size)()
    

    Although you probably want to go with a Python list, I'm not sure you need a ctypes array. Example:

    self._elements = [None] * size