2

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

4

1 回答 1

1

文档

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

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

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

于 2011-10-13T23:49:38.703 回答