properties of ctypes.py_object… here is a solution to the problem.
properties of ctypes.py_object
I’m trying to create a python array but have the following code issue
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 initialization, it creates an array using ctypes, the last two lines I don’t quite understand. I tried changing them to 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'
Can anyone help me explain?
Solution
ctypes.py_object
is a typectypes.py_object * size
is a typectypes.py_object()
is an instance of a type
What you have to do is first get the ctypes.py_object * size
type and then instantiate it:
self._elements = (ctypes.py_object * size)()
While you might want to use a Python list, I’m not sure if you need a ctypes array. Example:
self._elements = [None] * size