Cython:C 级 int 与 PyLongObjects

Cython: C-level int vs. PyLongObjects

我正在阅读 Kurt W. Smith 所著的《Cython》一书。我对这本书很困惑。

作者在第 42 页说:

In cases where Python built-in types like int or float have the same name as a C type, the C type takes precedence. This is almost always what we want.

然而在第44页,作者说:

Python also has a PyLongObject at the C level to represent arbitrarily sized integers. In Python 2, these are exposed as the long type, and if an operation with PyIntObject overflows, a PyLongObject results.

In Python 3, at the C level, all integers are PyLongObjects.

我的问题是如果我在Python3中声明了一个变量,比如

cdef int a;

a 是 C 级 int 因为 C 类型优先,还是 PyLongObject?

如果是C级int,第二部分怎么解读?

解决此类问题的最简单方法就是尝试一下,看看会发生什么:

$ cat > foo.pyx
cdef int mytestint
mytestint = 1
$ cython foo.pyx 
$ grep mytestint foo.c | head -n 1
static int __pyx_v_3foo_mytestint;

cdef int a在Python2和3中都声明了一个C级整数; C类型优先。

作者似乎在说 int in pure Python 3 总是表示 PyLongObject 类型。现在 Python intlong 数值类型之间没有区别。

Python 2 有 long 类型表示 PyLongObject 类型,但这已在 Python 3 中删除,只有 int 表示到 PyLongObject 类型。因此,在将 Cython 与 Python 一起使用时,当您编写 cdef long a 时,与内置类型没有潜在冲突 3.