如何创建一个固定长度,在用Cython Python对象的可变数组? [英] How do I create a fixed-length, mutable array of Python objects in Cython?

查看:602
本文介绍了如何创建一个固定长度,在用Cython Python对象的可变数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在创建数据结构特里要使用Python对象的数组。我需要将固定长度的结构像一个数组和可变像一个列表。我不想使用列表,因为我希望能够确保名单的究竟的大小合适(如果它开始分配额外的元素,内存开销可能加起来非常快的特里变大)。有没有办法做到这一点?我试图创建一个对象数组:

I need to have an array of python objects to be used in creating a trie datastructure. I need a structure that will be fixed-length like a tuple and mutable like a list. I don't want to use a list because I want to be able to ensure that the list is exactly the right size (if it starts allocating extra elements, the memory overhead could add up very quickly as the trie grows larger). Is there a way to do this? I tried creating an array of objects:

cdef class TrieNode:
    cdef object members[32]

...但是,这给了一个错误:

...but that gave an error:

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

什么是做什么,我试图做的最好方法是什么?

What is the best way to do what I'm trying to do?

推荐答案

我不知道有关的的解决方案,但这里的的解决方案:

I don't know about the best solution, but here's a solution:

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 对象是自动引用计数的PyObject * 。因为你采取的引用计数小家伙的责任,你总是可以只要推出自己的PyObject * 的的阵列。这可以是用于非平凡例主要头痛

A Cython object is an automatically refcounted PyObject *. You can always roll your own arrays of PyObject *'s as long as you take responsibility for refcounting the little buggers. This can be a major headache for non-trivial cases.

这篇关于如何创建一个固定长度,在用Cython Python对象的可变数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆