[Python-Dev] Possible C API problem?

Gary Robinson grobinson at goombah.com
Mon Jun 27 17:31:52 CEST 2005


Hello,

I was asking about a problem I was having over on the C++-python list, 
and they suggested I report it here as a possible Python problem.

I was getting bus errors with a C module I was linking to, so factored 
it down too a very small example that reproduced the problem. Here it 
is:


#include <Python.h>
static  double         gfSumChiSquare = 123.0; 
            
static PyObject *    
getSumChiSquare(PyObject *self, PyObject *args){
    return Py_BuildValue("d", gfSumChiSquare);
    }
    
static PyMethodDef SimMethods[] = {
    {"getSumChiSquare", getSumChiSquare, METH_NOARGS, "Return 
fSumChiSquare"},
    {NULL, NULL, 0, NULL}        /* Sentinel */
};

PyMODINIT_FUNC
inittestfloat(void)
{
    (void) Py_InitModule("testfloat", SimMethods);
}

That caused a bus error 100% of the time when I simply imported the 
module into Python and called getSumChiSquare(), i.e.:

>>> import testfloat
>>> testfloat.getSumChiSquare()
    

However, the problem seems to go away if I use METH_VARARGS, and parse 
the non-existent args with 
PyArg_ParseTuple:

#include <Python.h>
static  double         gfSumChiSquare = 123.0; 
            
static PyObject *    
getSumChiSquare(PyObject *self, PyObject *args){
    if (!PyArg_ParseTuple(args, "", NULL))
        return NULL;    
    return Py_BuildValue("d", gfSumChiSquare);
    }
    
static PyMethodDef SimMethods[] = {
    {"getSumChiSquare", getSumChiSquare, METH_VARARGS, "Return 
fSumChiSquare"},
    {NULL, NULL, 0, NULL}        /* Sentinel */
};

PyMODINIT_FUNC
inittestfloat(void)
{
    (void) Py_InitModule("testfloat", SimMethods);
}


This approach seems to work reliably -- at least variations I've tried 
haven't caused a bus error. But I haven't been able to discern an 
explanation from the docs as to why this would be better. The docs say 
that both METH_VARARGS and METH_NOARGS expect a PyCFunction. So if I am 
calling the function with no arguments, why can't I use METH_NOARGS and 
skip the call to PyArg_ParseTuple?

Could it be that this is a python bug? Or am I doing something wrong?

Note: this is using Python 2.3 on OS X:

    Python 2.3 (#1, Sep 13 2003, 00:49:11) 

Thanks in advance for any help or insight you can give,

Gary


-- 

Gary Robinson
CTO
Emergent Music, LLC
grobinson at goombah.com
207-942-3463
Company: http://www.goombah.com
Blog:    http://www.garyrobinson.net


More information about the Python-Dev mailing list