Jump to content

Check out our Community Blogs

Register and join over 40,000 other developers!

Recent Status Updates

View All Updates

- - - - -

Advanced Python, part 1: Extending Python with C

  • Please log in to reply
No replies to this topic

#1 spyder


    CC Resident

  • Just Joined
  • PipPipPipPip
  • 64 posts

Posted 31 July 2010 - 08:36 AM

This lesson in Advanced Python is going to teach C programmers how to implement some C programs in Python, on Windows and Linux, with only free compilers. I used MinGW for Windows which uses GCC, and just GCC on Linux. All of this was put together by the distutils module.

Non-os-specific information:
The first thing you need to do is include the Python header file.
You can find that in, C:\PythonXX\include(or download from the Ubuntu software center in Linux).
Get all the Python header files and put them in the same folder as your file.
Now the first line of your program is...
#include "Python.h"
Python.h include stdio.h and stdlib.h.
Then add an empty main function.
#include "Python.h"

int main() {
    return 0;
Now we start with our code.
First we need, our Python function.

static PyObject *
Your Python function name(PyObject *self, PyObject *args) #this is necessary
    int sts;
    sts = 0;
    return Py_BuildValue("i", sts);

This is your Python function.
It returns a Python object.
Now add your code.
To use the args you need to parse them.
Use PyArg_ParseTuple to do it.
There are several values you need to know.
Between C and Python value types are represented by letters.
i = integer,
l = long,
z = None,
s = string,
d = float/double,
D = complex(Py_Complex* in C),
O = PyObject*.

PyArg_ParseTuple converts your Python Arguments to C variables. You have to give PyArg_ParseTuple multiple arguments. The first is what you want to parse, the second is the format of the arguments, and the next however many arguments are the variables to store those arguments in. Py_BuildValue returns your format with whatever variables you give it.

We will make our function named system.
It will run system commands.
We will call the module foo.
#include "Python.h"

static PyObject *
foo_system(PyObject *self, PyObject *args) /*this is necessary*/
    char *command;
    if(!PyArg_ParseTuple(args, "s", &command))
        return None;
    sts = system(command);
    return Py_BuildValue("i", sts);

static PyMethodDef fooMethods[] = {
    {"system",  foo_system, METH_VARARGS, "Execute a shell(or command prompt) command."},
    {NULL, NULL, 0, NULL}

static struct PyModuleDef foomodule = {
   "foo",   /* name of module */
   NULL, /* module documentation, may be NULL */
   -1,       /* size of per-interpreter state of the module,
                or -1 if the module keeps state in global variables. */

    return PyModule_Create(&foomodule);

main(int argc, char *argv[])
    PyImport_AppendInittab("foo", PyInit_foo);
    return 0;
This is a big jump, but now we will explain it because it all goes together.
fooMethods is the functions in foo.
It takes a list ({}) of of the function name("system"), the function itself(foo_system),Wheter it is just args or keywords or nothing(METH_VARARGS), and the documentation.
You have to finish it with a {NULL, NULL, 0, NULL} so Python knows when to stop.:)
We then set up the module itself.
foomodule is a PyModuleDef and it defines the module.
It takes the PyModuleDef_HEAD_INIT as its start, then it takes the name, documentation, size of per-interpreter state or -1, and the Methods.
Then we have an Init funciton to initialize the Module.

Finally our main function does it all.
We initialize foo with PyImport_AppendInittab to make it so we can import it.
Then we Initialize it for good.
Now we make our setup script.

from distutils.core import setup, Extension

MOD = "foo"
setup(name = MOD,
		ext_modules = [Extension(MOD,sources=['foo.c'])],
		description = "My first C Extension Module")

All we do is name our module, give a description, and give it the extension sources.

Now for our Os specific stuff.
Now we have to compile it.
Open up the terminal and type
cd /path/to/your/folder/that/your/file/is/in
Then type:
python setup.py build
python setup.py install
When done you will have Python started, so try and import and use your module.

Open up the terminal and type
cd C:\path\to\your\folder\that\your\file\is\in
Then make sure you have MinGW installed. If you don't click here.
Make sure it is in your PATH system variable and type:
python setup.py build --compiler=mingw32
python setup.py install
and try and import and use your module.

Hope you understood and have fun.^^
  • 0
I C!(and Python, and C++, and ...)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download