我有以下调用 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/