cython 何时以及如何进行边界检查?

When and how does cython do boundscheck?

c 不进行边界检查。那么cython如何检查是否编译为c?

%%cython --annotate
cimport cython
@cython.boundscheck(True)
cpdef myf():
    cdef double pd[8]
    for i in range(100):
        pd[i] = 0
        print pd[i]

无论我为 boundscheck 设置 True 还是 False,以上代码都会编译为相同的 C 代码。如果我 运行 myf() 没有警告(碰巧没有崩溃...)。

更新

所以 cython 不会对 c 数组进行边界检查。

http://docs.cython.org/src/reference/compilation.html#compiler-directives

"Cython is free to assume that indexing operations ([]-operator) in the code will not cause any IndexErrors to be raised. Lists, tuples, and strings are affected..."

我认为在你的代码中,C 双精度数组不会在任何地方存储它的长度,因此 Cython 不可能做任何有用的检查(除了你非常简单的例子)。但是,可以引发 IndexErrors 的内置 Python 类型应该是不同的(我假设 numpy 数组、python 数组和 cython 内存视图也应该受到影响,因为它们都有一种机制让 Cython 判断它是否结束了)。