0

I am reading a book which is using ctypes to create C Array in python.

import ctypes

class Array:
    def __init__(self, size):        
        array_data_type = ctypes.py_object * size
        self.size = size
        self.memory = array_data_type()
        
        for i in range(size):
            self.memory[i] = None

I understand that self.memory = array_data_type() is creating a memory chunk which is basically a consecutive memory having ctypes.py_object * size as the total size.

How self.memory[i] is related to self.memory?

My understanding is that self.memory has no indexing and it is an object representing one single memory chunk.

meallhour
  • 13,921
  • 21
  • 60
  • 117
  • self.memory can also be assigned directly using self.memory = (ctypes.py_object * size)() – cup Mar 25 '22 at 07:01

1 Answers1

1

self.memory here is an array of NULL PyObject* pointers.

>>> import ctypes
>>> array_type = ctypes.py_object * 3
>>> array = array_type()
>>> array[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: PyObject is NULL

Which means self.array can contains three elements of type Pyobject(Any Python object). So this is valid.

>>> import ctypes
>>> array_type = ctypes.py_object * 3
>>> array = array_type()
>>> for i in range(3):
...     array[i] = f"{i}: test string"
...
>>> array._objects
{'0': '0: test string', '1': '1: test string', '2': '2: test string'}
Abdul Niyas P M
  • 18,035
  • 2
  • 25
  • 46
  • can you please provide more details on what you mean by `array of NULL PyObject*` pointers. `? – meallhour Mar 25 '22 at 07:08
  • 1
    @meallhour ctypes already provides an [`Array` class(result of `ctypes.py_object * 3`)](https://github.com/python/cpython/blob/main/Modules/_ctypes/_ctypes.c#L4804) which implements [`getitem`](https://github.com/python/cpython/blob/main/Modules/_ctypes/_ctypes.c#L4551). That's why you are able to index the array elements. – Abdul Niyas P M Mar 25 '22 at 10:05
  • 1
    Also when you instantiate a `ctypes.py_object` it will always be a `NULL PyObject*` pointer unless you pass a value(ie, `ctypes.py_object(10)`) – Abdul Niyas P M Mar 25 '22 at 10:10
  • thanks for all your inputs. What is complexity for `array_type = ctypes.py_object * 3`? Is it `O(1)` – meallhour Mar 26 '22 at 01:56
  • can you please provide your inputs to the question? https://stackoverflow.com/questions/71624787 – meallhour Mar 26 '22 at 02:41