Cython扩展类型中的Python字符串

时间:2011-07-29 13:43:59

标签: python cython

我有一个带字符串字段的扩展类型(cdef class)。我不知道宣布它的最佳方式是什么。假设以下代码:

cdef class Box:
    cdef char *_s
    cdef public str s1
    cdef public bytes s2

    property s:
        def __get__(self):
            cdef bytes py_string = self._s
            return py_string

    def __init__(self, s):
        cdef char *aux = s
        self._s = aux
        self.s1 = s
        self.s2 = s

使用扩展类型:

>>> import test as t
>>> b = t.Box("hello")
>>> b.s
'hello!'
>>> b.s1
'hello'
>>> b.s2
'hello'
>>> type(b.s)
<type 'str'>
>>> type(b.s1)
<type 'str'>
>>> type(b.s2)
<type 'str'>

它们都有效,但我不确定垃圾收集和字符串对象的生命周期等问题。我不喜欢char * +属性方法,因为它是三者中效率最低的。

所以我的问题是:这样做的最佳方法是什么?使用cdef public str s安全吗?

编辑:

只要cdef public str s的引用位于某个地方,Box似乎就可以正常工作。

>>> gc.collect()
0
>>> gc.is_tracked(b)
True
>>> gc.get_referrers(b.s1)
[<test.Box object at 0x1a4f680>]
>>> gc.get_referrers(b.s2)
[<test.Box object at 0x1a4f680>]
>>> b.s1
'hello'

感谢。

1 个答案:

答案 0 :(得分:0)

我不确定你为什么担心字符串的垃圾收集。

如果该字符串来自另一个C空间程序,那么只需复制其值,以便Box对象拥有它。