令我惊讶的是,没有关于将 Cython 数组转换为 Python 对象的文档。任何建议将不胜感激。
# Values are a list of integers containing numerators and denominators
def test_looping_ndarray_nd_list(list matrix):
cdef int *my_ints
cdef i
# Allocate memory to store ctype integers in memory
my_ints = <int *>malloc(len(matrix)*cython.sizeof(int))
if my_ints is NULL:
raise MemoryError()
for i in xrange(len(matrix)): # Convert to ctypes
my_ints[i] = matrix[i]
# How do I convert my_ints to Python object so I can return the result???
return
我会使用类型化的内存 View 来做到这一点:
import numpy as np
cimport numpy as np
cimport cython
# Values are a list of integers containing numerators and denominators
@cython.boundscheck(False)
def test_looping_ndarray_nd_list(list matrix):
cdef np.intp_t[:] my_ints
cdef int i
# Allocate memory to store ctype integers in memory
my_ints = np.array(matrix, dtype='int')
# do some work while releasing the GIL
with nogil:
for i in range(my_ints.shape[0]):
my_ints[i] = 2*my_ints[i]
return np.asarray(my_ints).tolist()
我是一名优秀的程序员,十分优秀!