我是 Python C-API 的新手,正在浏览一些源代码以获取其中的部分内容。
这是我在包含扩展模块的包的 C 源代码中找到的函数的最小版本:
#define PY_SSIZE_T_CLEAN
#include <Python.h>
static PyObject *
modulename_myfunc(PyObject *self, PyObject *args) {
// Call PyArg_ParseTuple, etc ...
// Dummy values; in the real function they are calculated
int is_found = 1;
Py_ssize_t n_bytes_found = 1024;
PyObject *result;
result = Py_BuildValue("(Oi)",
is_found ? Py_True : Py_False, // Py_INCREF?
n_bytes_found);
return result;
}
这是否会因为未能在 Py_True
或 Py_False
上使用 Py_INCREF
而引入小的内存泄漏? C-API docs for Boolean object似乎非常明确地总是需要增加/减少 Py_True
和 Py_False
。
如果确实需要引入 Py_INCREF
,如何在此处最恰本地使用它,假设 Py_RETURN_TRUE
/Py_RETURN_FALSE
不是真的适用,因为正在返回一个元组吗?
最佳答案
此处未使用 Py_INCREF
的原因是 Py_BuildValue
,当传递一个带有“O”的对象时,将为您增加引用计数:
O (object) [PyObject *]
Pass a Python object untouched (except for its reference count, which is incremented by one). If the object passed in is a NULL pointer, it is assumed that this was caused because the call producing the argument found an error and set an exception. Therefore, Py_BuildValue() will return NULL but won’t raise an exception. If no exception has been raised yet, SystemError is set.
您将在 CPython 中看到类似的用法 itself例如。
关于python - 递增 Py_True/Py_False refcount 总是必要的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58263736/