Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 895
Charlotte Avatar asked Aug 31 '25 21:08

Charlotte


1 Answers

  • ctypes.py_object is a type
  • ctypes.py_object * size is a type
  • ctypes.py_object() is an instance of a type

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
like image 193
Andrea Corbellini Avatar answered Sep 03 '25 10:09

Andrea Corbellini