扩展和嵌入Python解释器¶
本文档描述了如何在C或C中编写模块以使用新模块扩展Python解释器。 这些模块不仅可以定义新的功能,还可以定义新的对象类型及其方法。 该文档还介绍了如何将Python解释器嵌入到另一个应用程序中,用作扩展语言。 最后,它显示了如何编译和链接扩展模块,以便在底层操作系统支持此功能时,可以将动态(运行时)加载到解释器中。
本文档假设有关Python的基本知识。 有关语言的非正式介绍,请参阅Python教程。 Python语言参考给出了更正式的语言定义。 Python标准库记录了现有的对象类型,功能和模块(内置并以Python编写),为语言提供了广泛的应用范围。
有关整个Python / C API的详细说明,请参阅单独的Python / C API参考手册。
推荐的第三方工具¶
本指南仅涵盖用于创建作为此版本CPython的一部分提供的扩展的基本工具。 第三方工具,如Cython,cffi
,SWIG和Numba提供了更简单和更复杂的方法来创建Python的C和C扩展。
也可以看看
- Python包装用户指南:二进制扩展
- Python包装用户指南不仅涵盖了几种简化二进制扩展的创建的可用工具,还讨论了首先可能需要创建扩展模块的各种原因。
无需第三方工具创建扩展名¶
本指南的这一部分涵盖了无需第三方工具协助创建C和C扩展。 它主要用于这些工具的创建者,而不是推荐的创建自己的C扩展的方法。
- 1. 用C或C扩展Python
- 1.1. 一个简单的例子
- 1.2. Intermezzo:错误和异常
- 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.11. Writing Extensions in C++
- 1.12. Providing a C API for an Extension Module
- 2. Defining New Types
- 3. Building C and C++ Extensions
- 4. Building C and C++ Extensions on Windows
Embedding the CPython runtime in a larger application¶
Sometimes, rather than creating an extension that runs inside the Python interpreter as the main application, it is desirable to instead embed the CPython runtime inside a larger application. This section covers some of the details involved in doing that successfully.