在 Python 的 C/C++ 扩展中,返回的 PyObject* 应该具有什么引用计数

In C/C++ extensions to Python, what reference count should a returned PyObject* have?

本文关键字:引用 什么 返回 Python C++ 扩展 PyObject      更新时间:2023-10-16

假设你为python编写了一个C++(或C)扩展,称为module。它返回一个数组数组。返回的数组及其数组应该具有什么作为引用计数?

python代码是这样的

import my_module
from sys import getrefcount as g      # will use to check reference count
def use_module():
   x = my_module.func()
   print 'x =', x
   print 'g(x) =', g(x)
   print 'g(x[0]) =', g(x[0])
   test = 'some random thing'
   print 'should be', g(test), '?'
use_module()
>>> x = ( (1,2,3,4) , [2,3] , {'one':1} )
>>> g(x) = 3
>>> g(x[0]) = 3
>>> should be 2 ?

我希望g(x)2,而不是3。(添加g引用x后)

在我的C++扩展中,我确保数组及其所有子集合及其元素在返回给 python 之前具有 1 的引用计数,所以我不确定它是如何如此迅速地上升到3的?也许返回的PyObject*应该0作为其参考计数?

编辑:对不起,我是个白痴。我在不知情的情况下做了另一个参考。

如果不存在对返回对象的其他引用,则 refcount 应为 1。如果引用计数为 0,则对象将被解除分配。