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.

1
  • self.memory can also be assigned directly using self.memory = (ctypes.py_object * size)() Commented Mar 25, 2022 at 7:01

1 Answer 1

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'}
Sign up to request clarification or add additional context in comments.

5 Comments

can you please provide more details on what you mean by array of NULL PyObject* pointers. `?
@meallhour ctypes already provides an Array class(result of ctypes.py_object * 3) which implements getitem. That's why you are able to index the array elements.
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))
thanks for all your inputs. What is complexity for array_type = ctypes.py_object * 3? Is it O(1)
can you please provide your inputs to the question? stackoverflow.com/questions/71624787

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.