04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

362 CHAPTER 17 ■ EXTENDING PYTHON<br />

different languages to work together; your C (or C++) extension can then become a hub for the<br />

cooperation.<br />

INSTALLING SWIG<br />

By now, I guess you ought to be quite savvy about installing things. As before . . .<br />

• You can get SWIG from the Web site, http://www.swig.org.<br />

• Many UNIX/Linux distributions come with SWIG. Many package managers will let you install it directly.<br />

• There is a binary installer for Windows.<br />

• Compiling the sources yourself is again simply a matter of calling configure and make install.<br />

If you have problems installing SWIG, you should be able to find helpful information on the Web page.<br />

What Does It Do?<br />

Using SWIG is a simple process, provided that you have some C code:<br />

1. Write an interface file for your code. This is quite similar to C header files (and, for<br />

simple cases, you can use your header file directly).<br />

2. Run SWIG on the interface file, in order to automatically produce some more C code<br />

(wrapper code).<br />

3. Compile the original C code together with the generated wrapper code in order to<br />

generate a shared library.<br />

In the following, I discuss each of these steps, starting with a bit of C code . . .<br />

I Prefer Pi<br />

A palindrome (such as the title of this section) is a sentence that is the same when read backwards,<br />

if you ignore spaces and punctuation and the like. Let’s say you want to recognize huge<br />

palindromes, without the allowance for whitespace and friends. (Perhaps you need it for<br />

analyzing a protein sequence or something.) Of course, the string would have to be really big<br />

for this to be a problem for a pure Python program, but let’s say the strings are really big, and<br />

that you have to do lots and lots of these checks. You decide to write a piece of C code to deal<br />

with it (or perhaps you find some finished code—as mentioned, using existing C code in<br />

Python is one of the main uses of SWIG). Listing 17-3 shows a possible implementation.<br />

Listing 17-3. A Simple C Function for Detecting a Palindrome (palindrome.c)<br />

#include <br />

int is_palindrome(char *text) {<br />

int i, n=strlen(text);

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

Saved successfully!

Ooh no, something went wrong!