PyArg_ParseTuple导致分段错误 [英] PyArg_ParseTuple causing segmentation fault

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

问题描述

我正在尝试从扩展名中调用c函数,并将问题缩小到此测试用例.

I'm trying to call a c function from my extension and have narrowed the problem down to this test case.

#import "Python.h"

...

// Called from python with test_method(0, 0, 'TEST')
static PyObject*
test_method(PyObject *args)
{
    int ok, x, y, size;
    const char *s;

    // this causes Segmentation fault
    //ok = PyArg_ParseTuple(args, "iis#", &x, &y, &s, &size); 

    // also segfaults
    //if(ok) PyErr_SetString(PyExc_SystemError, 'Exception');

    // this does not cause segfault but fills the variables with garbage   
    ok = PyArg_ParseTuple(&args, "iis#", &x, &y, &s, &size);

    // Example: >test_method 0, 37567920, (garbage)
    printf(">test_method %d, %d, %s\n", x, y, s);

    /* Success */
    Py_RETURN_NONE;
}

static PyMethodDef testMethods[] =
{
     {"test_method", test_method, METH_VARARGS,
             "test_method"},
     ...

     {NULL, NULL, 0, NULL}
};

任何想法我可能做错了什么. (Python版本2.6.4).

Any ideas what I might be doing wrong. (Python version 2.6.4).

推荐答案

嗯.我认为您的方法的签名应该是这样的:

Hmmm. I think the signature of your method should be this:

static PyObject* test_method(PyObject* self, PyObject* args)

如果您将test_method作为绑定方法(即某些对象实例的方法)调用,则self将是对象本身.如果test_method是模块函数,则self是初始化模块时传递给Py_InitModule4()的指针(如果使用Py_InitModule(),则为NULL).事实是,Python在代码级别没有区分绑定实例方法和普通函数,这就是为什么即使要实现普通函数也必须传递self的原因.

If you are invoking your test_method as a bound method (i.e. a method of some object instance), self will be the object itself. If test_method is a module function, self is the pointer passed to Py_InitModule4() when you initialized the module (or NULL if you used Py_InitModule()). The thing is that Python makes no distinctions between bound instance methods and ordinary functions at the code level, that's why you have to pass self even if you are implementing a plain function.

有关更多详细信息,请参见此页面.

See this page for more details.

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

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