MLhacker
MLhacker

Reputation: 1512

How do I convert Cython array to Python object so I can return the result?

I'm flabbergasted that there is no documentation on converting a Cython array to a Python object. Any suggestion would be much appreciated.

# 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 

Upvotes: 2

Views: 406

Answers (1)

ngoldbaum
ngoldbaum

Reputation: 5580

I would do this using typed memoryviews:

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

Upvotes: 3

Related Questions