# 扩展和嵌入 Python 解释器

This document describes how to write modules in C or C++ to extend the Python interpreter with new modules. Those modules can do what Python code does -- define functions, object types and methods -- but also interact with native libraries or achieve better performance by avoiding the overhead of an interpreter. The document also describes how to embed the Python interpreter in another application, for use as an extension language. Finally, it shows how to compile and link extension modules so that they can be loaded dynamically (at run time) into the interpreter, if the underlying operating system supports this feature.

This document assumes basic knowledge about C and Python. For an informal introduction to Python, see Python 教程. Python 语言参考手册 gives a more formal definition of the language. Python 标准库 documents the existing object types, functions and modules (both built-in and written in Python) that give the language its wide application range.

关于整个 Python/C API 的详细介绍，请参阅独立的 Python/C API 参考手册。

To support extensions, Python's C 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"`.

备注

C 扩展接口特指 CPython，扩展模块无法在其他 Python 实现上工作。在大多数情况下，应该避免写 C 扩展，来保持可移植性。举个例子，如果你的用例调用了 C 库或系统调用，你应该考虑使用 `ctypes` 模块或 cffi 库，而不是自己写 C 代码。这些模块允许你写 Python 代码来接口 C 代码，并且相较于编写和编译 C 扩展模块，该方法在不同 Python 实现之间具有更高的可移植性。

## 推荐的第三方工具

This document only covers the basic tools for creating extensions provided as part of this version of CPython. Some third party tools offer both simpler and more sophisticated approaches to creating C and C++ extensions for Python.

While this document is aimed at extension authors, it should also be helpful to the authors of such tools. For example, the tutorial module can serve as a simple test case for a build tool or sample expected output of a code generator.

## C API Tutorial

This tutorial describes how to write a simple module in C or C++, using the Python C API -- that is, using the basic tools provided as part of this version of CPython.

1. 你的第一个 C API 扩展模块

## Guides for intermediate topics

本指南的这一部分包括在没有第三方工具帮助的情况下创建 C 和 C++ 扩展。它主要用于这些工具的创建者，而不是建议你创建自己的 C 扩展的方法。

- Using the C API: Assorted topics

- 自定义扩展类型：教程

- 定义扩展类型：杂项主题

- 构建 C/C++ 扩展

- 在 Windows 上构建 C 和 C++ 扩展

## 在更大的应用程序中嵌入 CPython 运行时

有时，不是要创建在 Python 解释器中作为主应用程序运行的扩展，而是希望将 CPython 运行时嵌入到更大的应用程序中。 本节介绍了成功完成此操作所涉及的一些细节。

- 在其它应用程序中嵌入 Python