Call C program

Daniel Fetchinson fetchinson at googlemail.com
Thu Dec 3 06:54:50 EST 2009


> I am developing a Python application and I need to call a C program which
> needs one parameter and it returns another one.

You mean you need to call a C function from python? Here is an example
with a C function that adds two integers:


/***************************** call this source file mymod.c
***********************************/
#include <Python.h>

/* This is the function 'add' that will be accessible from python */
static PyObject *add( PyObject * self, PyObject * args )
{
    const int i, j;
    int k;

    if( !PyArg_ParseTuple( args, "ii", &i, &j ) )
        return NULL;
    k = i + j;
    return Py_BuildValue( "i", k );
}

/* Here we tell python that the function 'add' should indeed be
accessible from python */
static PyMethodDef AddMethods[] = {
    {"add", add, METH_VARARGS, "Add two integers."},
    {NULL, NULL, 0, NULL}
};

/* This tells python that we have an extension module called 'mymod' */
PyMODINIT_FUNC initmymod( void )
{
    ( void ) Py_InitModule( "mymod", AddMethods );
}
/************************************************************************/


Once we have the above C file with the function 'add' we create a
setup.py for compiling it:


###########################################
from distutils.core import setup, Extension

# we define that our C function should live in the python module mymod
mymod = Extension( 'mymod', sources = ['mymod.c'])

# this will tell setup that we want to build an extension module
setup ( name = 'PackageName',
        version = '1.0',
        description = 'This is a demo package',
        ext_modules = [ mymod ] )
###########################################

Okay, so we have mymod.c and setup.py. You compile it with

python setup.py build

Now look into the 'build' directory, it will contain another directory
called lib.something. In this directory there is the compiled mymod.so
shared object file, which is ready to use:

[fetchinson at fetch lib.linux-x86_64-2.6]$ python
Python 2.6.1 (r261:67515, Mar 29 2009, 14:31:47)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-33)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mymod
>>> mymod.add(1,2)
3
>>> dir(mymod)
['__doc__', '__file__', '__name__', '__package__', 'add']


Have fun!

Cheers,
Daniel


-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown



More information about the Python-list mailing list