#

# A Brief Introduction to writing Python extension modules

Interfacing any language to Python involves building a module which can be loaded by the Python interpreter, but which isn't written in Python. This is known as an extension module. Many of the built-in Python libraries are constructed in 'C' this way; Python even supplies its fundamental types using the same mechanism. An extension module can be statically linked with the Python interpreter, but it more commonly resides in a shared library or DLL.

As you can see from The Python Extending and Embedding Tutorial, writing an extension module normally means worrying about

- maintaining reference counts
- how to call back into Python
- function argument parsing and typechecking

This last item typically occupies a great deal of code in an extension module. Remember that Python is a completely dynamic language. A callable object receives its arguments in a tuple; it is up to that object to extract those arguments from the tuple, check their types, and raise appropriate exceptions. There are numerous other tedious details that need to be managed; too many to mention here. The Boost Python Library is designed to lift most of that burden.

Another obstacle that most people run into eventually when extending Python is that there's no way to make a true Python class in an extension module. The typical solution is to create a new Python type in the extension module, and then write an additional module in 100% Python. The Python module defines a Python class which dispatches to an instance of the extension type, which it contains. This allows users to write subclasses of the class in the Python module, almost as though they were sublcassing the extension type. Aside from being tedious, it's not really the same as having a true class, because there's no way for the user to override a method of the extension type which is called from the extension module. BPL solves this problem by taking advantage of Python's metaclass feature to provide objects which look, walk, and hiss almost exactly like regular Python classes. BPL classes are actually cleaner than Python classes in some subtle ways; a more detailed discussion will follow (someday).

Next: Comparisons with Other Systems Up: Top

© Copyright David Abrahams 2000. Permission to copy, use, modify, sell and distribute this document is granted provided this copyright notice appears in all copies. This document is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose.