PyArg_ParseTuple在CApi中的SegFaults

时间:2011-10-13 21:31:43

标签: python numpy python-c-api

我正在编写代码,试图习惯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

1 个答案:

答案 0 :(得分:1)

来自the docs

  

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

     

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

你正在归还一个被盗的参考资料。先增加它。

相关问题