16.01.2014 Views

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

SHOW MORE
SHOW LESS

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

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

CHAPTER 17 ■ EXTENDING PYTHON 369<br />

Once you’ve got your function in place, there is still some extra wrapping needed <strong>to</strong> make<br />

your C code act as a module. But let’s get back <strong>to</strong> that once we’ve got a real example <strong>to</strong> work<br />

with, shall we?<br />

Palindromes, Detartrated 1 for Your Pleasure<br />

Without further ado, I give you the hand-coded <strong>Python</strong> C API version of the palindrome<br />

module (with some interesting new stuff added) in Listing 17-6.<br />

Listing 17-6. Palindrome Checking Again (palindrome2.c)<br />

#include <br />

static PyObject *is_palindrome(PyObject *self, PyObject *args) {<br />

int i, n;<br />

const char *text;<br />

int result;<br />

/* "s" means a single string: */<br />

if (!PyArg_ParseTuple(args, "s", &text)) {<br />

return NULL;<br />

}<br />

/* The old code, more or less: */<br />

n=strlen(text);<br />

result = 1;<br />

for (i=0; i

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

Saved successfully!

Ooh no, something went wrong!