代码之家  ›  专栏  ›  技术社区  ›  jtm

导致分段错误的PyArg\u ParseTuple

  •  0
  • jtm  · 技术社区  · 14 年前

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

    1 回复  |  直到 14 年前
        1
  •  1
  •   Tamás    14 年前

    嗯。我想你的方法应该是这样的:

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

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

    this page