O'Reilly logo

Python in a Nutshell, 2nd Edition by Alex Martelli

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Extending Python with Python’s C API

A Python extension module named x resides in a dynamic library with the same filename (x.pyd on Windows; x.so on most Unix-like platforms) in an appropriate directory (often the site-packages subdirectory of the Python library directory). You generally build the x extension module from a C source file x.c whose the overall structure is:

#include <Python.h>

/* omitted: the body of the x module */

void
initx(void)
{
    /* omitted: the code that initializes the module named x */
}

When you have built and installed the extension module, a Python statement import x loads the dynamic library, then locates and calls the function named initx, which must do all that is needed to initialize the module object named x.

Building and Installing C-Coded Python Extensions

To build and install a C-coded Python extension module, it’s simplest and most productive to use the distribution utilities, distutils, covered in The Distribution Utilities (distutils). In the same directory as x.c, place a file named setup.py that contains the following statements:

from distutils.core import setup, Extension
setup(name='x', ext_modules=[ Extension('x',sources=['x.c']) ])

From a shell prompt in this directory, you can now run:

C:\> python setup.py install

to build the module and install it so that it becomes usable in your Python installation. distutils performs all needed compilation and linking steps, with the right compiler and linker commands and flags, and copies the resulting dynamic ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required