Converting a Python List to a C double *

Alex Martelli aleax at aleax.it
Fri Apr 26 13:07:27 EDT 2002


<posted & mailed>

Joakim Hove wrote:

> 
> Hello,
> 
> I am writing a C-extension, and now I need to parse a list from python
> into a c double *:
> 
>    static PyObject * power(PyObject *self, PyObject *args) {
>      double *xdata;
>    
>      /*
>        This routine shall be called from Python. It will always be
>        called with a variable length list of floats: e.g.
>        module.power([0.1, 0.2, 0.45, 0.60, 0.70]).
>      
>        Within the c-function "power" I want to access the list in the
>        pointer xdata. How to parse?
>      */

/* warning, untested code, so there might be bugs, but the general
   idea would be something like: */

    PyObject* thelistofdoubles;
    int listlength;
    int i;
    PyObject* temp;

    if(!PyArg_ParseTuple(args, "O", &thelistofdoubles))
        return 0;
    if(!PySequence_Check(thelistofdoubles)) {
        PyErr_SetString(PyExc_TypeError, "argument must be a sequence");
        return 0;
    }
    listlength = PySequence_Size(thelistofdoubles);
    if(listlength<0)
        return 0;
    xdata = malloc(listlength * sizeof(double));
    for(i=0; i<listlength; i++) {
        temp = PySequence_GetItem(thelistofdoubles, i);
        if(!temp) {
            free(xdata);
            return 0;
        }
        if(!PyFloat_Check(temp)) {
            Py_DECREF(temp);
            free(xdata);
            PyErr_SetString(PyExc_TypeError, "all items must be float");
            return 0;
        }
        xdata[i] = PyFloat_AS_DOUBLE(temp);
        Py_DECREF(temp);
    }    


>      for (i=0; i<5; i++)
>        printf("x[%d] = %12.7f \n",i,xdata[i]);

Of course, you'll need to let i go no higher than listlength, which may
well be < 5, ot else risk a crash.

>      return PyNone();
>    }
> 
> Grateful for any suggestions -

Hope this helps...


Alex




More information about the Python-list mailing list