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 ...

Get Python in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.