# Cython

**Cython** 是面向 [Python](https://www.edgepedia.org/zh/python-programming-language) 编程语言以及扩展的 Cython 语言（后者基于 Pyrex）的优化静态编译器。它把 Python 代码翻译成 C 或 C++ 代码，再编译为 Python 扩展模块，并增加了用于调用 C 函数、为变量和类属性声明 C 类型的语言构造。<sup>[1](https://github.com/cython/cython.github.io/blob/master/index.html)</sup><sup> • </sup><sup>[2](https://github.com/cython/cython)</sup> 该项目自称是使用最广泛的 Python 到 C 编译器，在 PyPI 上每月下载量超过 7000 万次。<sup>[2](https://github.com/cython/cython)</sup>

| 关键事实 | 详情 |
|---|---|
| 是什么 | 面向 Python 及扩展 Cython 语言（基于 Pyrex）的优化静态编译器<sup>[1](https://github.com/cython/cython.github.io/blob/master/index.html)</sup> |
| 起源 | 最初基于坎特伯雷大学的 Greg Ewing 所开发的 Pyrex；于 2000 年代初作为一个项目启动<sup>[2](https://github.com/cython/cython)</sup> |
| 构建流程 | `.pyx`（或 `.py`）文件被翻译为 `.c` 文件，再由 C 编译器转换为可导入的 `.so`（Windows 上为 `.pyd`）模块<sup>[3](https://cython.readthedocs.io/en/latest/src/userguide/source_files_and_compilation.html)</sup> |
| 提速机制 | 静态类型声明让 Cython 生成更简单、更快的 C 代码，有时可快上几个数量级<sup>[4](https://cython.readthedocs.io/en/latest/src/quickstart/cythonize.html)</sup> |
| 无类型声明的收益 | 编译未添加类型声明的纯 Python 脚本，通常可获得约 20%–50% 的提速<sup>[5](https://cython.readthedocs.io/en/latest/src/tutorial/pure.html)</sup> |
| 许可证 | Apache 许可证（最初的 Pyrex 采用“无限制”许可）<sup>[2](https://github.com/cython/cython)</sup> |
| 参考论文 | Behnel、Bradshaw、Citro、Dalcin、Seljebotn 与 Smith，《Cython: The Best of Both Worlds》，《Computing in Science and Engineering》13.2:31-39（2011）<sup>[6](https://research.google/pubs/cython-the-best-of-both-worlds/)</sup> |

## 编译如何工作

与普通 Python 不同，Cython 代码必须经过编译，过程分为两个阶段。首先，`.pyx` 或 `.py` 文件由 Cython 翻译为包含 Python 扩展模块代码的 `.c` 文件。其次，C 编译器把该文件编译为类 Unix 系统上的 `.so` 共享库，或 Windows 上的 `.pyd` 文件，可直接导入 Python 会话。<sup>[3](https://cython.readthedocs.io/en/latest/src/userguide/source_files_and_compilation.html)</sup>

存在多种构建途径。`cython` 命令只把源码翻译为 C 或 C++；`cythonize` 命令还会把结果编译为可导入的扩展模块，而 `cythonize -a -i filename.pyx` 会就地构建，同时生成源码的带注释 HTML 报告。对于包，可由 setuptools（通过 `setup.py` 中的 `cythonize()`）、meson、配合 scikit-build-core 的 CMake，或 hatchling 等构建后端负责编译与打包。`pyximport` 可以像导入 `.py` 文件一样导入 `.pyx` 文件，在后台完成编译。<sup>[3](https://cython.readthedocs.io/en/latest/src/userguide/source_files_and_compilation.html)</sup><sup> • </sup><sup>[7](https://cython.readthedocs.io/en/latest/src/quickstart/build.html?source=post_page---------------------------)</sup>

**编译器指令**控制生成代码的行为，例如 `boundscheck`、`wraparound`、`initializedcheck` 和 `profile`。它们可以在头部注释中设置（`# cython: language_level=3, boundscheck=False`），在命令行上用 `-X` 设置，作为装饰器或 `with` 语句用于局部代码块，或通过 `cythonize()` 的 `compiler_directives` 参数设置。显式的按文件指令和局部指令优先于传给 `cythonize()` 的值。禁用 `boundscheck` 可能把本会引发 `IndexError` 的越界访问变成段错误或数据损坏；文档称，最安全的做法是只对完全不处理负索引的代码应用 `wraparound=False`。<sup>[3](https://cython.readthedocs.io/en/latest/src/userguide/source_files_and_compilation.html)</sup><sup> • </sup><sup>[8](https://cython.readthedocs.io/en/latest/src/userguide/source_files_and_compilation.html?highlight=cythonize)</sup>

## Cython 语言与静态类型

Cython 是带有 C 数据类型的 Python：几乎任何 Python 代码都是合法的 Cython 代码，编译器会把它转换为对 Python/C API 做等价调用的 C 代码。参数和变量可以用 C 数据类型声明，Python 值与 C 值可以自由混用并自动转换，Python 操作的引用计数和错误检查仍保持自动。<sup>[9](https://cython.readthedocs.io/en/latest/src/tutorial/cython_tutorial.html)</sup>

由于 Python 运行时的晚绑定是它相对于 C++ 等早绑定语言较慢的主要原因，Cython 通过早绑定获得速度。[静态类型](https://www.edgepedia.org/zh/static-typing)是一种便利而非必需，当类型声明不能带来优化、却仍强制进行类型检查时，甚至可能拖慢代码。<sup>[10](https://cython.readthedocs.io/en/latest/src/userguide/language_basics.html)</sup> 编译器支持两种语法风格：传统的 Cython `cdef` 语法，以及使用 PEP 484 类型提示和 PEP 526 变量注解的纯 Python 风格。函数可声明为 `def`（可从 Python 调用）、`cdef`（可从 C 调用）或 `cpdef`（两者皆可调用）。<sup>[10](https://cython.readthedocs.io/en/latest/src/userguide/language_basics.html)</sup><sup> • </sup><sup>[11](https://cython.readthedocs.io/en/latest/src/userguide/language_basics.html?highlight=include)</sup>

Cython 使用三种文件类型：后缀为 `.py` 或 `.pyx` 的实现文件；后缀为 `.pxd` 的定义文件，用于存放声明（类似 C 头文件），通过 `cimport` 使用；以及后缀为 `.pxi` 的包含文件，以文本方式被包含。大多数 `.py` 文件无需修改代码即可重命名为 `.pyx`，但 `cdef` 等扩展 Cython 语法只在 `.pyx` 文件中可用。<sup>[11](https://cython.readthedocs.io/en/latest/src/userguide/language_basics.html?highlight=include)</sup><sup> • </sup><sup>[12](https://cython.readthedocs.io/en/latest/src/userguide/faq.html)</sup>

Cython 3.0 将 Python 3 语法和语义设为默认，使用 `language_level=3str` 设置，其中无前缀字符串是 `str` 对象。一个值得注意的向后不兼容变化是：`x: int` 现在把 `x` 标注为精确的 Python `int`，而 Cython 0.29 接受任意 Python 对象。<sup>[13](https://cython.readthedocs.io/en/latest/src/userguide/migrating_to_cy30.html)</sup>

## 与 C 和 C++ 对接

Cython 的主要用途之一是封装已有的 C 库。外部 C 函数和变量通过指明头文件的 `cdef extern from` 块来声明；Cython 本身不读取 C 头文件，因此必须以 Cython 语法提供声明。C 标准库和 CPython C-API 的现成声明文件随 `Cython/Includes/` 包一同发布，因此可以直接 cimport `libc.math` 中的 `sin()` 等函数。<sup>[14](https://cython.readthedocs.io/en/latest/src/userguide/external_C_code.html?highlight=extern)</sup><sup> • </sup><sup>[15](https://cython.readthedocs.io/en/latest/src/tutorial/external.html)</sup>

这座桥是双向的。Cython 模块可以让 Python 代码调用 C 代码，并且通过 `public` 声明，它可以生成头文件，使与该模块链接的外部 C 代码能够调用 Cython 定义的函数并使用 Cython 定义的类型。<sup>[14](https://cython.readthedocs.io/en/latest/src/userguide/external_C_code.html?highlight=extern)</sup> C++ 也受支持：标记为 `# distutils: language = c++` 的 `.pyx` 文件会编译为 C++，`cdef cppclass` 块用于声明 [C++ 类](https://www.edgepedia.org/zh/c-classes)，常见的封装模式是把 C++ 实例作为 `cdef class` 的属性持有，并提供转发方法。<sup>[16](https://cython.readthedocs.io/en/latest/src/userguide/wrapping_CPlusPlus.html)</sup>

对于数值计算，带类型的内存视图可以高效访问内存缓冲区（例如 NumPy 数组底层的缓冲区），而不带来 Python 开销。从几乎任何通过 PEP 3118 缓冲区接口暴露可写缓冲区的对象都可获得内存视图，它支持索引、切片和转置，且无需持有 GIL。<sup>[17](https://cython.readthedocs.io/en/latest/src/userguide/memoryviews.html)</sup>

## GIL、并行与自由线程

Python 的全局解释器锁（GIL）保护解释器数据不被破坏，Cython 允许对不接触 Python 对象的代码释放它。释放它的两个主要原因是 Cython 的并行机制（其中 `prange` 循环的循环体必须是 `nogil`），以及允许其他 Python 线程并发运行。函数可在签名中标记为 `nogil`，或使用 `@cython.nogil` 装饰器，这表示适合无 GIL 执行，而不是释放锁本身；`with nogil:` 和 `with gil:` 块管理实际的释放与重新获取。<sup>[18](https://cython.readthedocs.io/en/latest/src/userguide/nogil.html)</sup>

文档提醒，单线程代码无论有无 GIL 运行速度相同，并且不得把 GIL 当作通用锁使用，因为执行任何 Python 代码（包括通过 `__del__` 进行对象销毁）都可能释放它。<sup>[18](https://cython.readthedocs.io/en/latest/src/userguide/nogil.html)</sup> Cython 3.1 还能构建与 Python 自由线程构建（无 GIL）兼容的扩展模块；默认情况下，此类模块会导致解释器在导入时重新启用 GIL，除非模块声明 `# cython: freethreading_compatible = True`。<sup>[19](https://cython.readthedocs.io/en/latest/src/userguide/freethreading.html)</sup>

## 纯 Python 模式

纯 Python 模式让同一个 `.py` 文件既能在解释器下运行，又能用 Cython 编译。编译未添加类型声明的纯 Python 脚本通常只能获得约 20%–50% 的提速；若要更进一步，可通过增补的 `.pxd` 文件、PEP 484/526 注解，或特殊 `cython` 模块的函数与装饰器来添加静态类型，这些方式可以组合使用。<sup>[5](https://cython.readthedocs.io/en/latest/src/tutorial/pure.html)</sup> 在纯模式下，代码被限制在 Python 中可表达或可模拟的范围加上类型声明；超出此范围的功能需要 `.pyx` 文件。`cython.cimports` 包名在 Python 语法中代替 `cimport`，此类代码在普通 Python 中运行会失败。<sup>[5](https://cython.readthedocs.io/en/latest/src/tutorial/pure.html)</sup>

## 与其他 Python 编译器的比较

该项目自己的比较列出了当前仍有相关性的类似工具。PyPy 是带有 JIT 编译器的 Python 实现，完全符合语言规范，但它是非 CPython 运行时，对 CPython 扩展的兼容性有限。Numba 是面向语言子集的基于 LLVM 的 JIT 编译器，主要针对 NumPy 数值代码。Pythran 是面向语言子集的静态 Python 到 C++ 编译器，可作为 Cython 中 NumPy 代码的附加后端。mypyc 是基于 mypy 静态分析器的静态 Python 到 C 编译器，与 Cython 的纯 Python 模式一样可使用 PEP 484 注解，但不提供底层优化。Nuitka 是高度符合语言规范的静态 Python 到 C 编译器，但同样缺乏底层优化和类型支持。<sup>[2](https://github.com/cython/cython)</sup>

与这些工具相比，该项目声称：对几乎所有 Python 特性（包括动态特性和内省）具有高度合规的支持；与各 CPython 版本完全运行时兼容；“一次生成，到处编译”的 C 代码生成；支持包括 PyPy 和 Pyston 在内的其他 C-API 实现；以及可手动调优至 C 层面。<sup>[2](https://github.com/cython/cython)</sup>

## 受限 API 与稳定 ABI

Python 的受限 API 是 C API 的安全子集，使用它享有稳定 ABI 保证：模块编译一次即可在未来 Python 版本上工作，无需重新编译。Cython 从 3.1 起支持以受限 API 模式编译，接近功能完整，主要好处是一个编译好的模块支持一系列 Python 版本。存在限制：`cdef` 类不能继承内置类型，不支持性能分析和行追踪，此模式下带类型的内存视图要求 Python 3.11 或更高版本。<sup>[20](https://cython.readthedocs.io/en/latest/src/userguide/limited_api.html)</sup>

该模式有可测量的性能代价。用常规 C API 编译 Cython 编译器本身，比不编译它快 38%；而以受限 API 编译，则根据所用 API 版本快 18%–33%。在 Python 3.12 及更高版本上，Cython 在受限 API 模式下使用 vectorcall 接口，可在不增加功能的情况下提升性能。<sup>[20](https://cython.readthedocs.io/en/latest/src/userguide/limited_api.html)</sup>

## 历史与采用情况

Cython 于 2000 年代初作为一个项目启动，最初基于 Pyrex——一种用于编写 Python 扩展模块的语言，由新西兰基督城[坎特伯雷大学](https://www.edgepedia.org/zh/university-of-canterbury)的 Greg Ewing 开发；Pyrex 采用“无限制”许可。<sup>[2](https://github.com/cython/cython)</sup> 2011 年，Stefan Behnel（Senacor Technologies）、Robert Bradshaw（谷歌）、Craig Citro、Lisandro Dalcin、Dag Sverre Seljebotn（[奥斯陆大学](https://www.edgepedia.org/zh/university-of-oslo)）和 Kurt Smith 在《Computing in Science and Engineering》上发表文章，将该语言介绍为解决 Python 在数值循环中的开销，以及高效使用现有 C 和 Fortran 代码之困难的方法。<sup>[6](https://research.google/pubs/cython-the-best-of-both-worlds/)</sup><sup> • </sup><sup>[21](https://citeseerx.ist.psu.edu/document?doi=ad99e8010f5733514d20c12f7427266b5ca5793a&repid=rep1&type=pdf)</sup>

采用范围广泛：该项目报告 PyPI 每月下载量超过 7000 万次，GitHub 仓库约有 10.8k 星标和 1.6k 派生仓库，用户群包括数千个库、包和工具。<sup>[2](https://github.com/cython/cython)</sup> 编译时间一直是一个已知痛点：对 2007 年以来各版本的问题追踪分析发现编译时间稳步增长，接近 Cython 3.0 时出现三倍跃升，与 Cython 从 Pyrex 分叉时相比总体约慢 30 倍。<sup>[22](https://github.com/cython/cython/issues/3646)</sup> 从 Cython 3.3 起，编译器要求至少 Python 3.9。<sup>[8](https://cython.readthedocs.io/en/latest/src/userguide/source_files_and_compilation.html?highlight=cythonize)</sup>

## References

1. [Cython: C-Extensions for Python, cython.org (site source)](https://github.com/cython/cython.github.io/blob/master/index.html)
2. [cython/cython README, GitHub](https://github.com/cython/cython)
3. [Source Files and Compilation, Cython 3.3.0 documentation](https://cython.readthedocs.io/en/latest/src/userguide/source_files_and_compilation.html)
4. [Faster code via static typing, Cython documentation](https://cython.readthedocs.io/en/latest/src/quickstart/cythonize.html)
5. [Pure Python Mode, Cython 3.3.0 documentation](https://cython.readthedocs.io/en/latest/src/tutorial/pure.html)
6. [Cython: The Best of Both Worlds, Google Research](https://research.google/pubs/cython-the-best-of-both-worlds/)
7. [Building Cython code, Cython documentation](https://cython.readthedocs.io/en/latest/src/quickstart/build.html?source=post_page---------------------------)
8. [Source Files and Compilation (cythonize page), Cython 3.3.0 documentation](https://cython.readthedocs.io/en/latest/src/userguide/source_files_and_compilation.html?highlight=cythonize)
9. [Basic Tutorial, Cython 3.3.0 documentation](https://cython.readthedocs.io/en/latest/src/tutorial/cython_tutorial.html)
10. [Language Basics, Cython 3.3.0 documentation](https://cython.readthedocs.io/en/latest/src/userguide/language_basics.html)
11. [Language Basics (file types), Cython 3.2.0a0 documentation](https://cython.readthedocs.io/en/latest/src/userguide/language_basics.html?highlight=include)
12. [FAQ, Cython 3.3.0 documentation](https://cython.readthedocs.io/en/latest/src/userguide/faq.html)
13. [Migrating from Cython 0.29 to 3.0, Cython documentation](https://cython.readthedocs.io/en/latest/src/userguide/migrating_to_cy30.html)
14. [Interfacing with External C Code, Cython 3.3.0 documentation](https://cython.readthedocs.io/en/latest/src/userguide/external_C_code.html?highlight=extern)
15. [Calling C functions, Cython 3.3.0 documentation](https://cython.readthedocs.io/en/latest/src/tutorial/external.html)
16. [Using C++ in Cython, Cython 3.3.0 documentation](https://cython.readthedocs.io/en/latest/src/userguide/wrapping_CPlusPlus.html)
17. [Typed Memoryviews, Cython 3.3.0 documentation](https://cython.readthedocs.io/en/latest/src/userguide/memoryviews.html)
18. [Cython and the GIL, Cython 3.3.0 documentation](https://cython.readthedocs.io/en/latest/src/userguide/nogil.html)
19. [Free threading, Cython 3.3.0 documentation](https://cython.readthedocs.io/en/latest/src/userguide/freethreading.html)
20. [The Limited API and Stable ABI, Cython 3.3.0 documentation](https://cython.readthedocs.io/en/latest/src/userguide/limited_api.html)
21. [Behnel et al., Cython: The Best of Both Worlds (PDF), CiteSeerX](https://citeseerx.ist.psu.edu/document?doi=ad99e8010f5733514d20c12f7427266b5ca5793a&repid=rep1&type=pdf)
22. [cython3.0: 3x compile-time regression compared to 0.29, GitHub issue #3646](https://github.com/cython/cython/issues/3646)

---
*Initially written Sep 17, 2026 · Reviewed: Sep 30, 2026; Oct 15, 2026 · Edited: Sep 30, 2026; Oct 15, 2026 · Last review: Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 软件与编程 › Programming languages › Individual programming languages › C-family and imperative languages

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/cython

English original: https://www.edgepedia.org/cython
