gpt4 book ai didi

python - Python C 扩展中的引用计数

转载 作者:太空狗 更新时间:2023-10-29 18:09:11 30 4
gpt4 key购买 nike

我正在为 Python 编写我的第一个 C 扩展,并且对我的引用计数感到困惑。这就是我想要做的。

我在 for 循环中填充一个字典:

mydict = PyDict_New();

for (...)
{
pair = PyTuple_Pack(2, PyString_FromString("some string"),
PyString_FromString("some other string"));

/* at this point, the refcnt for the tuple is 1, the refcnts for the
2 string items are 2. Because according to the source, PyString_FromString
does an INCREF, and PyTuple_Pack() does an INCREF on its items
*/

PyDict_SetItem(mydict, PyString_FromString("some key"), pair);

/* At this point, the key's refcnt is 2. PyString_FromString sets it to 1 and
PyDict_SetItem INCREF's it. Ditto for pair since PyDict_SetItem also INCREF's
the value.
*/

Py_DECREF(pair);

/* pair's refcnt is 1 which makes sense to me since mydict now owns the tuple,
but the refcnt for its items are still at 2. I don't understand this part.
*/
}

return mydict;

我的引用计数正确吗?在 C API 文档中,它特别推荐使用 PyObject_FromXXX用作 PyTuple_SetItemPyList_SetItem 的参数,因为它们“窃取”了引用。

没有记录 PyDict_SetItem 是否窃取引用。我猜在这种情况下不会,我应该做的

first = PyString_FromString("some string");
second = PyString_FromString("some other string");
pair = PyTuple_Pack(2, first, second);
Py_DECREF(second);
Py_DECREF(first);

我说得对吗?

最佳答案

如果您查看 PyTuple_Pack 的 CPython 源代码 (Objects/tupleobject.c),您会发现它确实会增加每个打包对象的引用计数。如果您改为执行 PyTuple_New,然后调用 PyTuple_SetItem,则不需要减少引用计数,因为 SetItem 会窃取引用。

最后,您可能只想使用 Py_BuildValue("(ss)", "some string", "some other string");它将为您构建您的元组,并为您创建 PyStrings: http://docs.python.org/c-api/arg.html#Py_BuildValue

关于python - Python C 扩展中的引用计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8528483/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com