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.

CHAPTER 17 ■ EXTENDING PYTHON 371<br />

SWIG. SWIG is a tool for automatically generating wrapper code for your C libraries. The<br />

wrapper code takes care of the Python C API so you don’t have to. It is one of the easiest<br />

and most popular ways of extending Python.<br />

Using the Python/C API. You can write C code yourself that can be imported directly into<br />

Python as shared libraries. To do this, you have to adhere to the Python/C API. Things you<br />

have to take care of for each function include reference counting, extracting arguments,<br />

and building return values. There is also a certain amount of code needed to make a C<br />

library work as a module, including listing the functions in the module and creating a<br />

module initialization function.<br />

New Functions in This Chapter<br />

Function<br />

Py_INCREF(obj)<br />

Py_DECREF(obj)<br />

PyArg_ParseTuple(args, fmt, ...)<br />

PyArg_ParseTupleAndKeywords(args, kws, fmt, kwlist)<br />

PyBuildValue(fmt, value)<br />

Description<br />

Increment reference count of obj<br />

Decrement reference count of obj<br />

Extract positional arguments<br />

Extract positional and keyword<br />

arguments<br />

Build a PyObject from a C value<br />

What Now?<br />

Now you ought to either have some really cool programs or at least some really cool program<br />

ideas. Once you’ve got something you want to share with the world (and you do want to share<br />

your code with the world, don’t you?), the next chapter can be your next step.

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

Saved successfully!

Ooh no, something went wrong!