如何获取PyObject的引用计数?

时间:2022-02-04 16:54:12

How to get reference count of a PyObject from C++?

如何从C ++获取PyObject的引用计数?

There are functions Py_INCREF and Py_DECREF which increase/decrease it, but I haven't found any function which return object's reference count.

有函数Py_INCREF和Py_DECREF增加/减少它,但我没有找到任何返回对象引用计数的函数。

I need it for debugging purposes.

我需要它用于调试目的。

1 个解决方案

#1


12  

The reference count of each and every object is stored in the PyObject itself, in a variable called ob_refcnt. You can directly access that.

每个对象的引用计数存储在PyObject本身的一个名为ob_refcnt的变量中。你可以直接访问它。

typedef struct _object {
    _PyObject_HEAD_EXTRA
    Py_ssize_t ob_refcnt;          # Reference count
    struct _typeobject *ob_type;
} PyObject;

Alternatively, you can use the Py_REFCNT Macro.

或者,您可以使用Py_REFCNT宏。

#1


12  

The reference count of each and every object is stored in the PyObject itself, in a variable called ob_refcnt. You can directly access that.

每个对象的引用计数存储在PyObject本身的一个名为ob_refcnt的变量中。你可以直接访问它。

typedef struct _object {
    _PyObject_HEAD_EXTRA
    Py_ssize_t ob_refcnt;          # Reference count
    struct _typeobject *ob_type;
} PyObject;

Alternatively, you can use the Py_REFCNT Macro.

或者,您可以使用Py_REFCNT宏。