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?
*/
for (i=0; i<5; i++)
printf("x[%d] = %12.7f \n",i,xdata[i]);
return PyNone();
}
Grateful for any suggestions -
Joakim Hove
--
==== Joakim Hove www.phys.ntnu.no/~hove/ =======================
|| Institutt for fysikk (735) 93637 / E3-166 | Skøyensgate 10D ||
|| N - 7491 Trondheim ho...@phys.ntnu.no | N - 7030 Trondheim ||
================================================= 73 93 31 68 =========
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
> xdata = malloc(listlength * sizeof(double));
Joakim's platform may have not the Cornucopia version of malloc() but
the Mother Hubbard version -- a test of the returned value may be a
good idea.
thank you very much for a detailed suggestion. It works just as I
intended :-)
Joakim