Unpacking a python list in C?
Fernando Pérez
fperez528 at yahoo.com
Thu May 2 13:39:00 EDT 2002
Richard P. Muller wrote:
> I need some help with extending python in C. I want to call a function
> of a list from python:
>
> answer = my_function(my_list)
>
> where my_function is a function, and my_list is a python list of floats.
> I want my_function to be a C function, and want to extract my_list into
> an integer length and a double * pointing to the values. I spent some
> time searching through the extension guide in the docs, but either this
> isn't there or I missed the section in which it is discussed. I also
> flipped through a few of my python books without luck.
>
> Could some kind soul take pity on me and tell me how to do this? Thanks
> in advance...
>
> Rick
Alex gave you the -perfectly correct- low-level answer. Now for the easy one
;) Use weave: http://scipy.org/
I assume (you are doing quantum chemistry after all) that everyting you do is
done with Numeric arrays (not real python lists), or can be done that way
(since you are going to convert to double *, this sounds like a valid
assumption). In that case, weave with the blitz converters makes short work
of this kind of problem.
Here:
http://windom.colorado.edu/~fperez/python/misc/python-c.pdf
you'll find a pdf with a simple illustrative example, and here:
http://windom.colorado.edu/~fperez/python/misc/weave_examples.html
is some example code I wrote when teaching myself this stuff. If you change
.html for .py in the above url you'll get a plaintext version you can save as
code for yourself.
Please note that this code requires CVS weave to work.
I'm not trying to demean Alex's solution, but for typical scientific
computing problems there's a very good chance you can completely bypass
writing at such a low level by using weave's various tools. It can be a huge
time-saver.
Cheers,
f.
More information about the Python-list
mailing list