在 Python 的 C/C++ 扩展中,返回的 PyObject* 应该具有什么引用计数
In C/C++ extensions to Python, what reference count should a returned PyObject* have?
假设你为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,则对象将被解除分配。
相关文章:
- 什么时候在C++中返回常量引用是个好主意
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- 在C++17中,引用const字符串的语义应该是什么
- 引用文件的适当方法是什么?
- 引用捕获和在 lambda 中通过引用发送参数有什么区别 (C++)
- C++有什么方法可以在既不调用函数模板也不提供其模板参数的情况下引用函数模板?
- 引用 std::any 或 not_yet_in_std::whatever 的惯用方式是什么?
- 在 Rust 中,指针和引用有什么区别?
- 为什么或在什么情况下,你会将参数作为C++中的引用(或指针)传递给函数?
- 获取通用/前向引用地址有什么意义?
- 返回引用实例和非引用实例(return mystr & vs mystr)之间的区别是什么?
- 删除对象(具有不同类型)的引用时会发生什么情况?
- 对于具有引用返回类型的搜索算法,默认返回值应该是什么?
- 普通的右值引用和 std::forward 返回的引用有什么区别?
- 通过引用函数传递指针参数是什么意思?
- C++ 中的引用范围是什么?
- 将引用绑定到指针的语法是什么?(各种)
- constexpr引用有什么用吗
- 对struct::struct的未定义引用是什么意思
- 什么是常量指针常量引用类型的参数?(const X* const & p)