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

标签 python c python-3.x python-c-api

我是 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/

相关文章:

python-3.x - Google 使用 selenium 搜索下一页

Python pandas - 访问其他列的 lambda 函数

python - 在 Python 3 中,单字节 (\xd0) 被打印为两个字节的序列 (\xc3\x90)

python - 将嵌套的 dict 打印到 tsv 格式文件

c - 使用 realloc 扩展结构数组

c++ - 通过 stdio 的 HTTP POST/GET

c++ - gtk_text_buffer_create_tag 创建警告 : 'GtkTextTag' has no property named '\u0004'

python - 异步上下文管理器

python - Python 的模板系统或语言(主要是 HTML)

python - 在py3中使用nltk时获取 "bad escape"