如何将Cython数组转换为Python对象,以便返回结果?

时间:2017-06-19 21:16:30

标签: python cython

我很惊讶没有关于将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 

1 个答案:

答案 0 :(得分:2)

我会使用类型化的内存视图来执行此操作:

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()