Cython 与 Numpy 数组
虽然Python
常因速度问题被人诟病,但实际科学计算应用时Numpy
大部分场合下可满足性能要求。必要情况下,将程序中的热点用Cython
重写能极大地提高运行速度。那么问题来了,需要与Cython
模块外的Numpy
数组互动怎么办最好?让我们来看看如何在 Numpy
数组 与 C 动态数组间转换。
内存视图(Memory View)
cef view = <int[:]> ndarr
cdef np.complex128_t[:,:] view = <np.complex128_t[:n,:m]> c_pointer
数组转为C指针
<int *> &ndarr[0]
这里的 ndarr 应当是 C_continuous
的。传入参数可以通过以下形式来保证这点:
def func(np.ndarray[double, ndim=2, mode="c"]):
pass
将内存传给数组
在C下分配的内存要传给数组相对就要麻烦一些,因为要考虑释放的问题。
import numpy as np
cimport numpy as np
cdef pointer_to_numpy_array(void * ptr, np.npy_intp size):
'''Convert c pointer to numpy array.
The memory will be freed as soon as the ndarray is deallocated.
author: Kynan & Stefan (http://stackoverflow.com/questions/23872946/)
'''
cdef extern from "numpy/arrayobject.h":
void PyArray_ENABLEFLAGS(np.ndarray arr, int flags)
cdef np.ndarray[np.npy_byte, ndim=1] arr = np.PyArray_SimpleNewFromData(1, &size, np.NPY_BYTE, ptr)
PyArray_ENABLEFLAGS(arr, np.NPY_OWNDATA)
return arr
之后可以用 arr.view(dtype)
将数据转成你想要的类型。