Python C 模块函数参数引用计数

标签 python c python-module python-c-api cpython

当我有一个从 PyArg_ParseTuple 获得的 PyObject * 时,我是否需要确保在从函数返回之前 Py_DECREF 它?

例子:

static PyObject * modulefunc(PyObject * self, PyObject * args) {
    PyObject * obj;
    if (!PyArg_ParseTuple(args, "O", &obj)) {
        return NULL;
    }

    if (!PyObject_TypeCheck(obj, expected_type_ptr)) {
        // Do I need to Py_DECREF(obj) here?
        PyErr_SetString(PyExc_TypeError, "First argument is not expected type.");
        return NULL;
    }

    // ... rest of function implementation.
}

最佳答案

没有。 PyArg_ParseTuple 给你一个 borrowed reference .

关于Python C 模块函数参数引用计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9892634/

相关文章:

c - 指向字符串 C 的指针

python - 为什么 getattr 的行为与手动更新对象不同

python - Python 是如何调用 in-imported 模块的?

python - 在 theading.Thread 中使用 sqlalchemy scoped_session

python - Google App Engine 是否与 Python translate() 兼容?

python - 自引用列表

python - 复杂阵列的智能打印

c++ - C 文件的 Eclipse CDT 索引器结果与 C++ 文件不同

c - 使用 va_args 打印另一个参数

python - __name__ ==“__main__”怎么办?