Mixing Python and C

This tutorial has been put together thanks to the work of:

Overview

Python is wonderful. C is wonderful. Do I need to choose? No!

This tutorial will show you how to create a program in which some is written in Python and some is written in C.

More specifically, you will be creating a Python C extension module, which you can import into Python as any module. You will also see how to call a C function from Python, and a Python function from C.

Goal

The goal of this tutorial is for your to write the program illustrated below

  • the main() function calls the say_hello() method from the hello module, which happens to be written in C.

  • During the execution of the say_hello()function, that function calls the sum() function, which happens to be written in Python.

Source Code

The source code consists of the following files:

  File Modified

File hellomodule.c

Apr 29, 2013 by Thomas Watteyne

File setup.py

Apr 29, 2013 by Thomas Watteyne

File test.py

Apr 29, 2013 by Thomas Watteyne

Building

The goal of the compilation step is to turn the hellomodule.c source code into a Python extension module called hello.pyd (Windows) or hello.so (Linux). Python comes with all the utilities to do so, but it needs a C compiler. On Linux, make sure you have gcc installed (this is almost always the case). On Windows, we recommend installing MinGW.

Building the extension module is driven by the setup.py file, which declares that you want to build a module called hello, and that it consists of the source file hellomodule.c. This is equivalent to a Makefile or an SConscript, if you're used to make or SCons.

To build the hello module, navigate to the directory containing this file and type:

under Linux:

python setup.py build

under Windows:

python setup.py build --compiler=mingw32

The resulting module will be placed at (for Windows) build/lib.win32-2.7/hello.pyd.

You can now see it as a regular Python module.

Running

Before running it, copy the hello.pyd module to the directory containing the other files. Double-click on the test.py script. The following text prints:

Result from myFunction:
Hello mehdi!
sum 3
Script ended normally. Press Enter to close.

Debugging

You can debug the Python intepretter directly through gdb. In Ubuntu, for example:

thomas@Thomas-X61s:~$ sudo gdb -ex r --args python openVisualizerWeb.py --sim --simCount=4 --simTopology=linear

 

References