In the Python Cookbook, Luther Blisset wrote a very useful class with
the Python C API. It takes a Python list of elements and copies it
member by member into a C array.
Here it is, (slightly modified by me):
static PyObject *totaldoubles(PyObject *self, PyObject *args) {
PyObject *seq, *item, *fitem;
double *dbar, result;
int i, seqlen;
if (!PyArg_ParseTuple(args, "O", &seq)) return NULL;
seq = PySequence_Fast(seq, "argument must be iterable");
if (!seq) return NULL;
seqlen = PySequence_Fast_GET_SIZE(seq);
dbar = malloc(seqlen * sizeof(double));
if (!dbar) { Py_DECREF(seq); return NULL; }
for (i=0; i < seqlen; i++) {
item = PySequence_Fast_GET_ITEM(seq, i);
if (!item) { Py_DECREF(seq); free(dbar); return NULL; }
fitem = PyNumber_Float(item);
if (!fitem) { Py_DECREF(seq); free(dbar); return NULL; }
dbar[i] = PyFloat_AS_DOUBLE(fitem);
Py_DECREF(fitem);
}
Py_DECREF(seq);
result = total(dbar, seqlen); /*call a C function using this array*/
free(dbar);
return Py_BuildValue("d", result);
}
I'd like to do the reverse: take an C array (say, with 100 elements)
and copy its elements into a Python list. But I don't know where to
start...there's no PySequence_Fast_INSERT or even PySequence_Insert
function, for example. Can I create an empty list in the API or
should I just pass one in from Python?
Can someone please help with this? Thanks in advance!!
--Nick