Calling C functions from a Python interpreter

by Girish Venkatachalam

Girish Venkatachalam is a UNIX hacker with more than a decade of networking and crypto programming experience. His hobbies include yoga,cycling, cooking and he runs his own business. Details here:

http://gayatri-hitech.com

http://spam-cheetah.com

There seem to be two ways to marry Python with C. One is called extending Python and another is called embedding Python. Embedding seems to be the tougher thing with extending being a subset of embedding Python.

There are also other advanced mechanisms using SWIG in which you can marry several scripting languages with C.

Python + C is very interesting and really easy.

First copy paste this file.

#include <Python.h>

/*
 * Function to be called from Python
 */
static PyObject* py_myFunction(PyObject* self, PyObject* args)
{
        char *s = "Hello from C!";
        return Py_BuildValue("s", s);
}

/*
 * Another function to be called from Python
 */
static PyObject* py_myOtherFunction(PyObject* self, PyObject* args)
{
        double x, y;
        PyArg_ParseTuple(args, "dd", &x, &y);
        return Py_BuildValue("d", x*y);
}

/*
 * Bind Python function names to our C functions
 */
static PyMethodDef myModule_methods[] = {
        {"myFunction", py_myFunction, METH_VARARGS},
        {"myOtherFunction", py_myOtherFunction, METH_VARARGS},
        {NULL, NULL}
};

/*
 * Python calls this to let us initialize our module
 */
void initpyfoo()
{
        (void) Py_InitModule("pyfoo", myModule_methods);
}


Name it as pyfoo.c .

This is important. You cannot have arbitrary names. If you give some other name then you also need initba() (if you name your file ba.c) instead of initpyfoo() as above inside the file.

Now compile it using this command on linux.

$ gcc -shared -I/usr/include/python2.5 -lpython2.5 -opyfoo.so pyfoo.c

It should go through. If not please find out why it doesn't work.

Then create a python file called whatever(this name doesn't matter).

from pyfoo import *

print "Result from myFunction():", myFunction()
print "Result from myOtherFunction():", myOtherFunction(4.0, 5.0)

Call it i.py and then

$ python i.py

will print this.

Result from myFunction(): Hello from C!
Result from myOtherFunction(): 20.0

So what did we do?

We just called C functions from inside python!

And the two most important Python methods are

PyArg_ParseTuple() which converts Python objects into C datatypes.

And

Py_BuildValue() which converts the C datatypes into Python objects.

This allows us to manipulate C variables and Python objects with either C or Python.

And remember to define the functions as static and every function invariably returns PyObject * .



Got something to add? Send me email.





(OLDER) <- More Stuff -> (NEWER)    (NEWEST)   

Printer Friendly Version

-> -> Calling C functions from a Python interpreter


6 comments



Increase ad revenue 50-250% with Ezoic


More Articles by © Girish Venkatachalam







Thu Sep 3 18:41:55 2009: 6843   TonyLawrence

gravatar
I never could seem to get into Python - I wrote this Python vs. Perl a while back:


(link)



Fri Sep 4 23:45:44 2009: 6858   drag

gravatar
Python has seemed to have taken over Linux by storm in the past few years. Pretty much every little new tool or applet seems to use it.

If your using Linux and you want to do some serious GUI programming there seems to be few things easier and better then the Python + Glade combination. Use a graphical GUI builder to build the UI that is described in XML. Write python program using gobject/gnome-style main loop and import your GUI as a class. Then its a matter of assigning methods to buttons and your off to a good start.

Of course it's used for more then that. The most impressive example is that I used OpenOCD to pull a firmware image from a Xscale/Windows CE via Jtag interface. Reverse engineered the proprietary wear levelling FTL layer and built a drive image that could be mounted in Linux using Fat32 drivers. :) The array datatype is invaluable for that sort of thing...

Microsoft uses trasaction-safe Fat FS + half microsoft-half custom FTL . Transaction safe Fat is Fat with two fat tables!! FTL is file to block translation layer that also has some wear leveling algorithms. Fun stuff.

The other favorite Python thing I like is Paste. Paste implements WSGI protocol for server-side python web scripting. WSGI is kinda like CGI but instead of the web server executing a interpreter it uses a standard protocol for communicating with separate long-running processes. So it's pretty easy to build decent server-side scripting without the risks of using python_mod and that sort of thing. Its a nice alternative for people who want to run web servers on things with low resources.

Of course another thing I like to mess around with is Blender3D. It's a entirely open source 3D animation and rendering application suite. Very nice. Includes a surprisingly capable gaming engine. Uses Python for it's scripting language.

Of course Perl can do all that stuff too (except for blender whatnot).

It's probably been posted before and will probably be a bit out of date with Python 3.x, but it's a nice thing for experienced programmers to get a handle on python quickly.
(link)

Another fantastic and actually fun thing is:
(link)

Its a web riddle were you need to use some sort of programming examples to solve. Once you solve a riddle then that gives you a password to unlock a section of the wiki were you can discuss the concepts and compared the solutions. Very cool. Taught me a lot. And it's fun for non-python programmers also.. there seems to be always a few comments were people are pointing out solutions in other languages.
(link)






Mon Sep 7 13:52:29 2009: 6866   anonymous

gravatar
What is the difference between C and PYTHON? Thanks!



Mon Sep 7 13:58:38 2009: 6867   TonyLawrence

gravatar
Python is an interpreter, like Perl. C is a compiled language. Syntactically, C is very different: see
(link)



Tue Jan 25 23:02:47 2011: 9253   anonymous

gravatar


seriously helpful article. good way to get up and started with c in python.

------------------------
Kerio Samepage


Have you tried Searching this site?

Unix/Linux/Mac OS X support by phone, email or on-site: Support Rates

This is a Unix/Linux resource website. It contains technical articles about Unix, Linux and general computing related subjects, opinion, news, help files, how-to's, tutorials and more.

Contact us