【问题标题】:What is the actual use in ob_sstate in python's string object structure?python的字符串对象结构中ob_sstate的实际用途是什么?
【发布时间】:2022-01-10 12:06:38
【问题描述】:

CPython中的字符串结构:

typedef struct {
    PyObject_VAR_HEAD
    long ob_shash;
    int ob_sstate;
    char ob_sval[1];

    /* Invariants:
     *     ob_sval contains space for 'ob_size+1' elements.
     *     ob_sval[ob_size] == 0.
     *     ob_shash is the hash of the string or -1 if not computed yet.
     *     ob_sstate != 0 iff the string object is in stringobject.c's
     *       'interned' dictionary; in this case the two references
     *       from 'interned' to this object are *not counted* in ob_refcnt.
     */
} PyStringObject;

ob_shash 成员包含哈希,我了解它的用法。但是ob_sstate 存储字符串是否被实习的信息。我浏览了很多函数,但找不到这个结构字段的使用位置?它是干什么用的?

【问题讨论】:

标签: python c cpython python-internals internals


【解决方案1】:

这是一种弱引用。来自Objects/stringobject.c

/* This dictionary holds all interned strings.  Note that references to
   strings in this dictionary are *not* counted in the string's ob_refcnt.
   When the interned string reaches a refcnt of 0 the string deallocation
   function will delete the reference from this dictionary.

   Another way to look at this is that to say that the actual reference
   count of a string is:  s->ob_refcnt + (s->ob_sstate?2:0)
*/
static PyObject *interned;

释放函数使用ob_sstate(通过PyString_CHECK_INTERNED 宏)知道它正在销毁一个内部字符串,以便将其从interned 中删除。实际上还有另一个值 SSTATE_INTERNED_IMMORTAL 仅“值得”一个参考。

【讨论】:

    猜你喜欢
    • 2018-02-02
    • 1970-01-01
    • 1970-01-01
    • 2011-04-02
    • 2019-05-17
    • 2015-04-22
    • 2021-07-22
    • 1970-01-01
    • 2021-04-14
    相关资源
    最近更新 更多