04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

370 CHAPTER 17 ■ EXTENDING PYTHON<br />

/* An initialization function for the module (the name is<br />

significant): */<br />

PyMODINIT_FUNC initpalindrome() {<br />

Py_InitModule("palindrome", PalindromeMethods);<br />

}<br />

Most of the added stuff in Listing 17-6 is total boilerplate. Where you see palindrome, you<br />

could insert the name of your module, while where you see is_palindrome, insert the name of<br />

your function. If you have more functions, simply list them all in the PyMethodDef array. One<br />

thing is worth noting, though: The name of the initialization function must be initmodule,<br />

where module is the name of your module; otherwise, Python won’t find it.<br />

So, let’s compile! You do this just like in the section on SWIG, except that there is only one<br />

file to deal with now. Here is an example using gcc (remember to add -fPIC in Solaris):<br />

gcc -I$PYTHON_HOME -I$PYTHON_HOME/Include -shared palindrome2.c -o palindrome.so<br />

Again, you should have a file called palindrome.so, ready for your use. Put it somewhere in<br />

your PYTHONPATH (such as the current directory) and away we go:<br />

>>> from palindrome import is_palindrome<br />

>>> is_palindrome('foobar')<br />

0<br />

>>> is_palindrome('deified')<br />

1<br />

And that’s it. Now go play. (But be careful; remember the Waldi Ravens quote from the<br />

Introduction.)<br />

A Quick Summary<br />

Extending Python is a huge subject. The tiny glimpse provided by this chapter included the<br />

following:<br />

Extension philosophy. Python extensions are useful mainly for two things: for using<br />

existing (legacy) code, or for speeding up bottlenecks. If you’re writing your own code<br />

from scratch, try to prototype it in Python, find the bottlenecks, and factor them out as<br />

extensions if needed. Encapsulating potential bottlenecks beforehand can be useful.<br />

Jython and IronPython. Extending these implementations of Python is quite easy: You<br />

simply implement your extension as a library in the underlying implementation (Java for<br />

Jython and C# or some other .NET language for IronPython) and immediately the code is<br />

usable in your Python.<br />

Extension approaches. There are plenty of tools for extending or speeding up your code:<br />

for making the incorporation of C code into your Python program easier, for speeding up<br />

common operations such as numeric array manipulation, or for speeding up Python itself.<br />

Such tools includ SWIG, Psyco, Pyrex, Weave, NumPy, ctypes, subprocess, and modulator.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!