CApi中的PyArg_ParseTuple SegFaults [英] PyArg_ParseTuple SegFaults in CApi

查看:231
本文介绍了CApi中的PyArg_ParseTuple SegFaults的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写代码,试图适应NumPy数组的C API.

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

这是精简版.我只希望能够获取类型为PyArrayObject的对象并将其返回.不幸的是,这也导致了SegFault.

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位,Python 2.7.1

Linux, 64-bit, Python 2.7.1

推荐答案

来自文档:

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

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!(对象)[ typeobject ,PyObject *]
将Python对象存储在C对象指针中.这类似于O,但是...

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.

这篇关于CApi中的PyArg_ParseTuple SegFaults的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆