开发者

Python strings in a Cython extension type

I have an extension type (cdef class) with a string field. I don't know what's the best way of declaring it. Assume the following code:

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

And using the extension type:

>>> 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'>

They all work, but I'm not sure about issues like garbage collection and the lifetime of the string objects. I don't like the char * + property approach since it's the most inefficient of the three.

So my question is: what's the best way of doing this? Is using cdef public str s safe?

EDIT:

Wel开发者_如何学Pythonl cdef public str s seems to work fine as long as a reference to the Box is held somewhere.

>>> 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'

Thanks.


I am not sure why you have concerns about the garbage collection of the string.

If that strings comes from another C-space program then just copy its value, so that the Box object owns it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜