Home > Back-end >  Creating "C Array" in Python
Creating "C Array" in Python

Time:03-26

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.

CodePudding user response:

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'}
  • Related