C code in Python

Robert Kern robert.kern at gmail.com
Fri Sep 1 23:20:27 EDT 2006


Tommy Grav wrote:
> I have some numerical code in C that I would like to call from Python. Can
> anyone point me in a direction for some text I could read on how to do this?

It somewhat depends on the kind of numerical code and the interface it exposes. 
Do you need to pass arrays back and forth? Is your interface limited to numbers, 
or will you need to pass strings and structures around, too (i.e. can the 
interface be as limited as FORTRAN 77 is? That would let you use f2py which is 
quite nice if you need to pass arrays around)?

If you need arrays, you will probably want to use numpy to represent them in Python.

   http://numpy.scipy.org

At the bottom of this page, you can read about a number of ways to interface C 
code with numpy.

   http://www.scipy.org/Cookbook

I would probably suggest using ctypes at this point unless you have reasons to 
otherwise. Some recent work has gone into making this option work well with 
numpy. With ctypes' inclusion in Python 2.5, this will probably become one of 
the more preferred methods of calling out to C code.

   http://www.scipy.org/Cookbook/Ctypes2
   http://starship.python.net/crew/theller/ctypes/

If that doesn't work out for you, and the many choices leave you bewildered, 
describe your C code and what you want the Python interface to look like, and 
then we can help you find a better tool for your needs.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list