gpt4 book ai didi

python - 递增 Py_True/Py_False refcount 总是必要的吗?

转载 作者:太空宇宙 更新时间:2023-11-03 15:30:18 24 4
gpt4 key购买 nike

我是 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_TruePy_False 上使用 Py_INCREF 而引入小的内存泄漏? C-API docs for Boolean object似乎非常明确地总是需要增加/减少 Py_TruePy_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/

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