扩展和嵌入 Python 解释器

本文档描述了如何使用 C 或 C++ 编写模块以使用新模块来扩展 Python 解释器的功能。 这些模块不仅可以定义新的函数,还可以定义新的对象类型及其方法。该文档还描述了如何将 Python 解释器嵌入到另一个应用程序中,以用作扩展语言。 最后,它展示了如何编译和链接扩展模块,以便它们可以动态地(在运行时)加载到解释器中,如果底层操作系统支持此特性的话。

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 built-ins reference documents the built-in functions and object types, and The Python standard library documents the modules (both built-in and written in Python) that give the language its wide application range.

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

不使用第三方工具创建扩展

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

参见

PEP 489 -- 多阶段扩展模块初始化

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

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