我正在编写代码,试图适应 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
请您参考如下方法:
来自 the docs :
O(object) [PyObject *]
Store a Python object (without any conversion) in a C object pointer. The C program thus receives the actual object that was passed. The object’s reference count is not increased. The pointer stored is not NULL.
O!(object) [typeobject, PyObject *]
Store a Python object in a C object pointer. This is similar toO, but...
您返回的是被盗的引用资料。先增加它。
