Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 9 Current »

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 in 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
You are not logged in. Any changes you make will be marked as anonymous. You may want to Log In if you already have an account.
No files shared here yet.
  • Drag and drop to upload or browse for files
  • 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 this consists of the source file hellomodule.c. This is equivalent to a Makefile or an SConscrip, 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 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
    Scrip 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

    • No labels