使用 PyDict_SetItemString 进行引用计数 [英] Reference counting using PyDict_SetItemString

查看:40
本文介绍了使用 PyDict_SetItemString 进行引用计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在 PyDict 中(在 C 扩展中)的现有字段中设置新值时,内存管理/引用计数是如何工作的.

I'm wondering how memory management/reference counting works when a new value is set into an existing field within a PyDict (within a C extension).

例如,假设按以下方式创建和填充字典:

For instance, assume a dictionary is created and populated in the following way:

myPyDict = PyDict_New();
tempPyObj = PyString_FromString("Original Value");
PyDict_SetItemString(myPyDict,"fieldname",tempPyObj);
Py_DECREF(tempPyObj);

从内存和引用计数的角度来看,当有后续事件时会发生什么

From a memory and reference counting perspective, what happens when there is a subsequent

tempPyObj = PyString_FromString("New Value");
PyDict_SetItemString(myPyDict,"fieldname",tempPyObj);
Py_DECREF(tempPyObj);

对原始值的引用计数是否自动递减(并自动释放内存)?

Is the reference count for the original value automatically decremented (and the memory automatically released)?

PyList_SetItem 的文档特别提到了列表会发生什么:此函数窃取"对项目的引用并丢弃对受影响位置列表中已有项目的引用.

The doc for PyList_SetItem specifically mentions what happens for lists: This function "steals" a reference to item and discards a reference to an item already in the list at the affected position.

但是 PyDic_SetItemPyDict_SetItemString 都没有说明如何处理字典的替换.

But neither PyDic_SetItem nor PyDict_SetItemString say how the replacement is handled for dictionaries.

推荐答案

PyList_SetItem 函数的逻辑会自动递减旧值的引用计数.您不应该自行减少旧值.

The ref count of the old value is decremented automatically by logic of PyList_SetItem function. You shouldn't be decrementing the old value by yourself.

如果您想了解详细信息,请查看 CPython 源代码,特别是 Objects/dictobject.c 文件.

If you want to know details, take a look at CPython source code, specifically at the Objects/dictobject.c file.

1) PyDict_SetItemString()

https://github.com/python/cpython/blob/c8e7c5a/Objects/dictobject.c#L3250-L3262

它是 PyDict_SetItem()

2) PyDict_SetItem()

https://github.com/python/cpython/blob/c8e7c5a/Objects/dictobject.c#L1537-L1565

仍然很简单,很明显,所有与在 dict 中插入/替换值相关的繁重工作实际上都是由 insertdict() 完成的.

Is still quite simple and it's obvious that all the heavy-lifting related to inserting/replacing values in a dict is actually done by insertdict().

3) insertdict()

https://github.com/python/cpython/blob/c8e7c5a/Objects/dictobject.c#L1097-L1186

是给我们答案的函数.在此函数中,您可以找到关键代码,尤其是调用:

is the function which gives us the answer. In this function you can find the crucial code and especially the call:

 Py_XDECREF(old_value); /* which **CAN** re-enter (see issue #22653) */

减少旧值的引用计数.

这篇关于使用 PyDict_SetItemString 进行引用计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆