Overview
The Python/C API gives C and C++ programmers access to the Python interpreter at multiple levels. There are two primary use cases:- Extension Modules - Write C modules that extend the Python interpreter with new functionality
- Embedding Python - Use Python as a component within a larger C/C++ application
Include Files
All Python/C API functionality requires including a single header:What Gets Included
ThePython.h header automatically includes:
<assert.h><inttypes.h><limits.h><math.h><stdarg.h><string.h><wchar.h>
All names defined by Python.h use the
Py or _Py prefix. Names beginning with _Py are internal and should not be used by extension writers.Objects and Reference Counts
Most Python/C API functions work withPyObject* - a pointer to an opaque type representing any Python object.
Key Concepts
- All Python objects live on the heap - never declare automatic/static
PyObjectvariables - Every object has a type and a reference count
- The reference count tracks how many references to the object exist
- When the reference count reaches zero, the object is deallocated
Basic Example
Error Handling
C programmers must explicitly check for errors. The Python/C API uses error indicators:- Functions return
NULL(for pointers) or-1(for integers) on error - An exception is set in thread-local storage
- Check with
PyErr_Occurred()or test return values
Error Handling Pattern
Useful Macros
Type Checking
Utility Macros
Return the smaller of two values
Return the larger of two values
Return absolute value (arguments may be evaluated multiple times)
Silence compiler warnings for unused function arguments
Thread Safety
Python uses a Global Interpreter Lock (GIL) to protect internal state:- Most API functions require holding the GIL
- Release the GIL for long-running operations
- Reacquire before calling Python APIs
Next Steps
Very High Level Layer
Execute Python code from C
Object Protocol
Work with Python objects
Reference Counting
Memory management fundamentals
Exception Handling
Handle and raise exceptions
See Also
- Python Packaging Guide: Binary Extensions
- PEP 7: Style Guide for C Code
- Third-party tools: Cython, cffi, pybind11, PyO3
