Python and C, arrays
olipt at mayo.edu
Sat Jun 12 00:22:41 CEST 1999
> Hey folks,
> I've run into a problem with a module I'm writing in C. Basically, I
> need to be able to convert Python tuples or lists (it's unimportant
> which) into C arrays. I know at compile-time the type of the array (and
> that the tuple or list will be homogeneous, and of compatible type), but
> I don't know the size.
> I then need to find a way to take a C array and stuff it back into a
> Python tuple or list. I have some ideas involving using "stack-like"
> lists or tuples in Python, with a "pop" function which I could call from
> C, repeated in a loop to get everything. But this seems overly complex,
> and indeed like it has the potential to become truly hideous.
There are lots of ways to do this. I'll let others respond with more
"standard" Python methods.
But, my favorite way to interface with homogeneous C arrays is using the C
API of the Numeric extension module:
c = PyArray_ContiguousFromObject(some_sequence,the_type,mindim,maxdim);
c->data is now a pointer to the C array.
PyArray_Return(c) returns the Numeric object to Python.
Note that the Numeric array can be just like any other sequence object.
But, if you must have a list you can use the tolist() method of the
More information about the Python-list