#
1. Extending Python with C or C++

It is quite easy to add new built-in modules to Python, if you know how to program in C. Such extension modules can do two things that can't be done directly in Python: they can implement new built-in object types, and they can call C library functions and system calls.

To support extensions, the Python API (Application Programmers Interface) defines a set of functions, macros and variables that provide access to most aspects of the Python run-time system. The Python API is incorporated in a C source file by including the header `"Python.h"`.

The compilation of an extension module depends on its intended use as well as on your system setup; details are given in later chapters.

Subsections

- 1.1 A Simple Example
- 1.2 Intermezzo: Errors and Exceptions
- 1.3 Back to the Example
- 1.4 The Module's Method Table and Initialization Function
- 1.5 Compilation and Linkage
- 1.6 Calling Python Functions from C
- 1.7 Extracting Parameters in Extension Functions
- 1.8 Keyword Parameters for Extension Functions
- 1.9 Building Arbitrary Values
- 1.10 Reference Counts
  - 1.10.1 Reference Counting in Python
  - 1.10.2 Ownership Rules
  - 1.10.3 Thin Ice
  - 1.10.4 NULL Pointers
- 1.11 Writing Extensions in C++
- 1.12 Providing a C API for an Extension Module