在 Python 中创建 "C Array"

Creating "C Array" in Python

我正在阅读一本使用 ctypes 创建 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

我知道 self.memory = array_data_type() 正在创建一个 memory chunk,它基本上是一个总大小为 ctypes.py_object * sizeconsecutive memory

self.memory[i]self.memory 有什么关系?

我的理解是self.memoryno indexing,是一个代表one single memory chunk.

的对象

self.memory 这里是一个 NULL PyObject* 指针数组。

>>> 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

表示self.array可以包含三个Pyobject(Any Python object)类型的元素。所以这是有效的。

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