首页 > 解决方案 > ctypes.py_object 的属性

问题描述

我正在尝试创建一个 python 数组,但下面的代码有问题

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

在初始化中,它使用 ctypes 创建一个数组,我不太了解最后两行。我试图将它们更改为一行

self._elements = ctypes.py_object() * size

但它不起作用并给我错误

TypeError: unsupported operand type(s) for *: 'py_object' and 'int'

谁能为我解释一下?

标签: pythonarrayspyobject

解决方案


  • ctypes.py_object是一种类型
  • ctypes.py_object * size是一种类型
  • ctypes.py_object()是一个类型的实例

您要做的是先获取ctypes.py_object * size 类型,然后实例化它:

self._elements = (ctypes.py_object * size)()

尽管您可能想要使用 Python 列表,但我不确定您是否需要 ctypes 数组。例子:

self._elements = [None] * size

推荐阅读