the attribute of 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'

谁能为我解释一下?

  • 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

您想使用()简单的删除括号进行多点处理,它将起作用

self._elements = ctypes.py_object * size

这将适用于self._elements = (size*ctypes.py_object)( )

相关内容

最新更新