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 * .
More Articles by Girish Venkatachalam
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. We appreciate comments and article submissions.
Many of the products and books I review are things I purchased for my own use. Some were given to me specifically for the purpose of reviewing them. I resell or can earn commissions from the sale of some of these items. Links within these pages may be affiliate links that pay me for referring you to them. That's mostly insignificant amounts of money; whenever it is not I have made my relationship plain. I also may own stock in companies mentioned here. If you have any question, please do feel free to contact me.
Specific links that take you to pages that allow you to purchase the item I reviewed are very likely to pay me a commission. Many of the books I review were given to me by the publishers specifically for the purpose of writing a review. These gifts and referral fees do not affect my opinions; I often give bad reviews anyway.
We use Google third-party advertising companies to serve ads when you visit our website. These companies may use information (not including your name, address, email address, or telephone number) about your visits to this and other websites in order to provide advertisements about goods and services of interest to you. If you would like more information about this practice and to know your choices about not having this information used by these companies, click here.
Click here to add your comments
Thu Sep 3 18:41:55 2009: TonyLawrence
I never could seem to get into Python - I wrote this Python vs. Perl a while back:
http://aplawrence.com/Unixart/pythonvsperl.html
Fri Sep 4 23:45:44 2009: drag
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.
http://diveintopython.org/
Another fantastic and actually fun thing is:
http://www.pythonchallenge.com/
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.
http://www.pythonchallenge.com/
Mon Sep 7 13:52:29 2009: anonymous
http://www.hxlimited.com
What is the difference between C and PYTHON? Thanks!
Mon Sep 7 13:58:38 2009: TonyLawrence
Python is an interpreter, like Perl. C is a compiled language. Syntactically, C is very different: see http://aplawrence.com/Linux/c_compiling_linux.html
Tue Jan 25 23:02:47 2011: anonymous
seriously helpful article. good way to get up and started with c in python.
Don't miss responses! Subscribe to Comments by RSS or by Email
Click here to add your comments
If you want a picture to show with your comment, go get a Gravatar