Python/C API中的引用计数
- void Py_INCREF(PyObject *o)
void Py_XINCREF(PyObject *0)
增加对象o的引用计数,后者可处理NULL,即若o为NULL,后者不会崩溃,前者则会崩溃。void Py_DECREF(PyObject *o)
- void Py_XDECREF(PyObject *o)
减小对象o的引用计数,前者不可处理NULL,但后者可以处理。当对象o的引用计数减小到0时,会调用对应类型的deallocation函数。
警告:The deallocation function can cause arbitrary Python code to be invoked (e.g. when a class instance with a __del__() method is deallocated). While exceptions in such code are not propagated, the executed code has free access to all Python global variables. This means that any object that is reachable from a global variable should be in a consistent state before Py_DECREF() is invoked. For example, code to delete an object from a list should copy a reference to the deleted object in a temporary variable, update the list data structure, and then call Py_DECREF() for the temporary variable.
- void Py_CLEAR(PyObject *o)
减小对象o的引用计数,可处理NULL。The warning for Py_DECREF() does not apply with respect to the object passed because the macro carefully uses a temporary variable and sets the argument to NULL before decrementing its reference count.
还有两个函数Py_IncRef(PyObject *o) 和 Py_DecRef(PyObject *o),分别对应宏Py_INCREF(PyObject *o) 和 Py_DECREF(PyObject *o)。
- 查看一个PyObject的引用计数,使用宏Py_REFCNT(PyObject *o)