Calling C functions in Python

Kitchi picture Kitchi · May 20, 2013 · Viewed 46.6k times · Source

I have a bunch of functions that I've written in C and I'd like some code I've written in Python to be able to access those functions.

I've read several questions on here that deal with a similar problem (here and here for example) but I'm confused about which approach I need to take.

One question recommends ctypes and another recommends cython. I've read a bit of the documentation for both, and I'm completely unclear about which one will work better for me.

Basically I've written some python code to do some two dimensional FFTs and I'd like the C code to be able to see that result and then process it through the various C functions I've written. I don't know if it will be easier for me to call the Python from C or vice versa.

Answer

Florian Rhiem picture Florian Rhiem · May 20, 2013

You should call C from Python by writing a ctypes wrapper. Cython is for making python-like code run faster, ctypes is for making C functions callable from python. What you need to do is the following:

  1. Write the C functions you want to use. (You probably did this already)
  2. Create a shared object (.so, for linux, os x, etc) or dynamically loaded library (.dll, for windows) for those functions. (Maybe you already did this, too)
  3. Write the ctypes wrapper (It's easier than it sounds, I wrote a how-to for that)
  4. Call a function from that wrapper in Python. (This is just as simple as calling any other python function)