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.
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.
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:
python setup.py build
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.
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:
Script ended normally. Press Enter to close.
You can debug the Python intepretter directly through gdb. In Ubuntu, for example: