Cython中的ctypedef与numpy:什么是正确的约定?

时间:2014-02-28 00:19:38

标签: python c numpy cython

在Cython中使用numpy时,写作的重点是什么:

cimport numpy as np
import numpy as np
ctypedef np.int_t DTYPE_t

然后在任何地方使用DTYPE_t而不只是使用np.int_tctypedef在结果代码中实际上做了什么不同的事情吗?

1 个答案:

答案 0 :(得分:2)

您可以阅读docs for cython中的注释,阅读他们解释使用此表示法和导入的原因的说明。

from __future__ import division
import numpy as np
# "cimport" is used to import special compile-time information
# about the numpy module (this is stored in a file numpy.pxd which is
# currently part of the Cython distribution).
cimport numpy as np
# We now need to fix a datatype for our arrays. I've used the variable
# DTYPE for this, which is assigned to the usual NumPy runtime
# type info object.
DTYPE = np.int
# "ctypedef" assigns a corresponding compile-time type to DTYPE_t. For
# every type in the numpy module there's a corresponding compile-time
# type with a _t-suffix.
ctypedef np.int_t DTYPE_t
# "def" can type its arguments but not have a return type. The type of the
# arguments for a "def" function is checked at run-time when entering the
# function.
#
# The arrays f, g and h is typed as "np.ndarray" instances. The only effect
# this has is to a) insert checks that the function arguments really are
# NumPy arrays, and b) make some attribute access like f.shape[0] much
# more efficient. (In this example this doesn't matter though.)