python - Python C API分配的一些资源是否需要释放

标签 python c

我有以下调用 Python API 库的 C 代码:

PyObject *obj;

PyObject *arguments;

arguments = PyTuple_New(2);

PyTuple_SetItem(arguments, 0, PyLong_FromLongLong(10));

PyTuple_SetItem(arguments, 1, PyLong_FromLongLong(20));

obj = PyObject_CallObject(my_function, arguments); // should "obj" be released after being used?

PyLong_AsLongLong(obj);

Py_DECREF(arguments); // is this instruction necessary?

我有两个问题(都在代码中作为注释),即:1) 变量 obj 在使用后是否应该释放(如果是,这是怎么做的?)和 2)我们是否需要减少变量arguments 的引用计数器(即我们是否需要 Py_DECREF(arguments);)?感谢您提前提供的所有帮助!

最佳答案

你应该阅读 https://docs.python.org/3/c-api/intro.html#objects-types-and-reference-counts ,它描述了使用 Python C API 处理引用计数的正确方法。按照那里描述的规则,适合您的情况的正确代码如下。

PyObject *obj;
PyObject *arguments;
arguments = PyTuple_New(2);  // this returns a new reference

// You don't need to Py_DECREF() the return values of PyLong_FromLongLong()
// because PyTuple_SetItem() steals a reference. 
PyTuple_SetItem(arguments, 0, PyLong_FromLongLong(10));
PyTuple_SetItem(arguments, 1, PyLong_FromLongLong(20));

obj = PyObject_CallObject(my_function, arguments); // this returns a new reference

PyLong_AsLongLong(obj);

Py_DECREF(arguments); // this is necessary because a new reference was created earlier
Py_DECREF(obj); // this is necessary because a new reference was created earlier

请注意,我没有添加任何错误检查。其中一些函数可以在出错时返回 NULL,因此检查它们是明智的。

关于python - Python C API分配的一些资源是否需要释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71348487/

相关文章:

Python:Pandas 数据框 - 数据被覆盖而不是连接

c - 换位密码编译太长

Python请求,如何为每个请求绑定(bind)不同的源ip?

Python AlsaLib 错误

python - 将 UNC 存储在 JSON 中并加载到字典中

python - 切片我的数据框返回意外结果

c - 仅使用 getchar() 从输入中获取整数并转换为 int

c - 为什么UDP socket通信不出错?

c++ - RegDeleteKey 失败并显示 ERROR_ACCESS_DENIED

c - 为什么循环后有一个换行符