python - 如何在 Cython 中创建固定长度、可变的 Python 对象数组?

标签 python arrays cython trie python-c-extension

我需要一个 python 对象数组来创建一个 trie 数据结构。我需要一个像元组一样固定长度、像列表一样可变的结构。我不想使用列表,因为我希望能够确保列表的大小完全正确(如果它开始分配额外的元素,内存开销可能会很快增加,因为trie 变得更大)。有没有办法做到这一点?我尝试创建一个对象数组:

cdef class TrieNode:
    cdef object members[32]

...但这给出了一个错误:

Error compiling Cython file:
------------------------------------------------------------
...
cdef class TrieNode:
    cdef object members[32]
                      ^
------------------------------------------------------------

/Users/jason/src/pysistence/source/pysistence/trie.pyx:2:23: Array element cannot be a Python object

做我想做的事情的最佳方法是什么?

最佳答案

我不知道最佳解决方案,但这是一个解决方案:

from cpython.ref cimport PyObject, Py_XINCREF, Py_XDECREF

DEF SIZE = 32

cdef class TrieNode:
    cdef PyObject *members[SIZE]

    def __cinit__(self):
        cdef object temp_object
        for i in range(SIZE):
            temp_object = int(i)
            # increment its refcount so it's not gc'd.
            # We hold a reference to the object and are responsible for
            # decref-ing it in __dealloc__.
            Py_XINCREF(<PyObject*>temp_object)
            self.members[i] = <PyObject*>temp_object

    def __init__(self):
        # just to show that it works...
        for i in range(SIZE):
            print <object>self.members[i]

    def __dealloc__(self):
        # make sure we decref the members elements.
        for i in range(SIZE):
            Py_XDECREF(self.members[i])
            self.members[i] = NULL

Cython object 是一个自动引用的 PyObject *。只要您负责对小错误进行重新计数,您就可以随时滚动自己的 PyObject * 数组。对于非平凡的情况,这可能是一个令人头疼的问题。

关于python - 如何在 Cython 中创建固定长度、可变的 Python 对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4834036/

相关文章:

python - 无法导入名称 import_by_path

python - 如何控制scikit-learn决策树算法的精度

php - 如何在 css 中使用 php 制作内容属性

python - cython char array[] convert 中的 c++ header wrapper 声明

c++ - Cython 和 C++ 类构造函数

python - 根据具有相同索引/列名称的另一个 DataFrame 中的值设置 Pandas DataFrame 中的单元格值

python - 在 python 中可视化推文长度

mysql - 使用 Ruby 将来自两个单独数组的值插入到 mysql 表中

javascript - For循环转换一系列变量

c++ - 模板类中的 Cython C++ 静态方法