【问题标题】:PyArg_ParseTuple causing segmentation faultPyArg_ParseTuple 导致分段错误
【发布时间】:2010-06-30 09:12:39
【问题描述】:

我正在尝试从我的扩展程序中调用一个 c 函数,并将问题缩小到这个测试用例。

#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)。

【问题讨论】:

    标签: python c argument-passing python-c-extension


    【解决方案1】:

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

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

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

    更多详情请见this page

    【讨论】:

    • 就是这样,出于好奇, *self 指的是什么?模块?
    • 我已经扩展了我的回复来回答这个问题。
    猜你喜欢
    • 1970-01-01
    • 2011-11-06
    • 2020-12-31
    • 2019-07-21
    • 2018-07-28
    • 2014-04-25
    • 2011-07-18
    • 2013-02-26
    • 2022-01-12
    相关资源
    最近更新 更多