PyArg_ParseTuple SegFaults in CApi

穿精又带淫゛_ 提交于 2019-12-11 00:18:08

问题


I am writing a code, trying to get used to the C API of NumPy arrays.

#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();
}

This is a stripped-down version. I just want to be able to get an object of type PyArrayObject and return it back. Unfortunately this gives a SegFault also.

Linux, 64-bit, Python 2.7.1


回答1:


From 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 to O, but...

You're returning a stolen reference. Increment it first.



来源:https://stackoverflow.com/questions/7760658/pyarg-parsetuple-segfaults-in-capi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!