【问题标题】:PyArg_ParseTuple SegFaults in CApiCApi 中的 PyArg_ParseTuple SegFaults
【发布时间】:2011-10-13 21:31:43
【问题描述】:

我正在编写代码,试图习惯 NumPy 数组的 C API。

#include <Python.h>
#include "numpy/arrayobject.h"
#include <stdio.h>
#include <stdbool.h>


static char doc[] =
"Document";

static PyArrayObject *
    trace(PyObject *self, PyObject *args){

    PyArrayObject *matin;

    if (!PyArg_ParseTuple(args, "O!",&PyArray_Type, &matin))
         return NULL;

    printf("a");
    return matin;
}

static PyMethodDef TraceMethods[] = {
    {"trace", trace, METH_VARARGS, doc},
    {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC
inittrace(void)
{
    (void) Py_InitModule("trace", TraceMethods);
    import_array();
}

这是一个精简版。我只想能够获得PyArrayObject 类型的对象并将其返回。不幸的是,这也会产生 SegFault。

Linux,64 位,Python 2.7.1

【问题讨论】:

    标签: python numpy python-c-api


    【解决方案1】:

    来自the docs

    O(对象)[PyObject *]
    将 Python 对象(无需任何转换)存储在 C 对象指针中。 C 程序因此接收传递的实际对象。 对象的引用计数没有增加。存储的指针不是NULL

    O! (object) [typeobject, PyObject *]
    将 Python 对象存储在 C 对象指针中。这类似于O,但是...

    您正在返回一个被盗参考。首先增加它。

    【讨论】:

    • 我不熟悉 C 语言的软件架构,但我想当我不使用 PYINCREF(the_python_object); 增加引用时,垃圾收集器会发现它的引用为 0,并释放该内存。 (如果我错了,请纠正我)
    • 基本上是的,但是是引用计数下降到 0 才调用 GC,而不是相反。
    猜你喜欢
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    • 2012-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多