2.1 Your First Python extension

Here's a minimal yet complete Python extension in C:

#include <Python.h>

PyMODINIT_FUNC
initfirst(void) 
{
	Py_InitModule3("first", NULL,
		       "Example module's docstring.");
}

Short, huh? Of course, this extension does almost nothing but it can be used to illustrate a few points.

Foremost of these is the process of turning C source into a Python extension. Nowadays this is pretty simple: put the above source in a file called 'firstmodule.c' and the following in a file called 'first-setup.py' in the same directory:

from distutils.core import setup, Extension

setup(name="first", version="1.0",
      ext_modules=[Extension("first", ["firstmodule.c"])])

Running

$ python first-setup.py build_ext -i

from a shell or DOS box should result in a ``dynamic shared object'' (``first.so'' on Unix variants or ``first.pyd'' on Windows) in the working directory. Run Python from that directory and you should be able to ``import first'', although the first module is pretty dull.

You'll notice that the module name - here ``first'' - occurs in three places: the name of the object file containing the extension code, the name of the ``module init function'' and in the call to Py_InitModule3.

When you execute import first, the interpreter finds the shared object file, looks for a function named ``initfirst'' and complains if executing that function fails to register a module called ``first''. So this module really is minimal.

For obvious reasons, it is customary for the module's name to also be part of the name of the file containing the C source.

I'll omit detailed instructions on how to compile other code samples and assume that you can generalize this one.

Python.h is usually the only Python specific file you need to include to gain access to the Python/C API. It is important that Python.h is the first header you include.

The distutils package takes care of the details of compiling your file so that this header is accessible.

Why Py_InitModule*3*? Well, there are variants of this function for historical reasons (which, yes, take 2 or 4 arguments), but there are no reasons to use them in new code.

The symbol PyMODINIT_FUNC is a preprocessor symbol provided by Python that contains the necessary dynamic linker magic your platform needs for the import of a dynamic extension to work. It is strongly advised that all other symbols in your extension are declared static.

With this experience under our belt, we move on to examples that actually do something.

THIS DOCUMENT IS A DRAFT! Comments to mwh@python.net please.