[Tutor] python lists to C arrays and vice versa
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Mon Feb 7 22:48:24 CET 2005
On Mon, 7 Feb 2005, Viktor Hornak wrote:
> I've been trying to find more resources/documentation about how to
> convert python lists to C arrays (and vice versa) when writing a python
> extension.
Hi Viktor,
There was a post back in 1999 that might be useful for you:
http://mail.python.org/pipermail/tutor/1999-November/000758.html
I'm not positive if there is a nicer helper function to do this.
> I also found one or two examples of similar operations on this list
> postings (from 6 years ago!) but they didn't quite explain all I need
> to know.
Ah, so you did see that posting then. *grin* Ok, good.
What parts of their explanation were incomplete? Maybe one of us here can
help fill in more details for you.
> Here is the code I was trying to use to convert two lists (one
> is a list of strings with the same length and the other is a list of
> doubles) to C arrays in a C extension:
[Some code cut]
The code there seems sorta ok: you might want to add a string length check
in there somewhere: the code expects that names are at most 4 characters
long, but that condition isn't being checked by strcpy().
> Then I call the function "parseMask" (which I am trying to wrap in this
> extension) which returns a C array (integer array, elements are either 0
> or 1). Now I need to convert this integer array to python list and
> return it back to python. Here is the code for that:
>
> result = (int *) malloc(sizeof(int) * nat);
> parseMask(...) -> returns int array result
>
> pylist = PyTuple_New(nat);
> for (i = 0; i < nat; i++) {
> /* convert resulting array [0/1] to PyObject */
> if (result[i] == 0)
> item = PyInt_FromLong(0);
> else
> item = PyInt_FromLong(1);
>
> PyTuple_SetItem(pylist, i, item);
> Py_DECREF(item); /** <-- (dyoo): bug located */
> }
Ah! Got it. Don't call Py_DECREF() here: PyTuple_SetItem will already
"steal" the reference, according to the documentation:
http://docs.python.org/api/tupleObjects.html#l2h-576
so there's no need to decrement the reference count here.
By the way, if you're really going to do more C extension stuff, take a
look at Pyrex or SWIG:
http://nz.cosc.canterbury.ac.nz/~greg/python/Pyrex/
http://www.swig.org/
Coding C wrappers by hand is painful: use these tools to make your life
easier. *grin*
Best of wishes!
More information about the Tutor
mailing list