Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list to Cython

I want to know how to convert normal python list to C list with Cython , process it and return a python list. Like:

Python script:

import mymodule

a = [1,2,3,4,5,6]
len = len(a)
print(mymodule.process(a,len))

Cython script (mymodule.pyd):

cpdef process(a, int len):
    cdef float y
    for i in range(len):
        y = a[i]
        a[i] = y * 2
    return a

I read about MemoryView and many others things but I not really unterstand what happen and a lot of example use Numpy ( I don't want to use it for avoid user of my script download a big package ... anyway I think it's don't work with my software ). I need a really simple example to understand what's happening exactly.

like image 776
Jean-Francois Gallant Avatar asked Feb 08 '13 19:02

Jean-Francois Gallant


1 Answers

You'll need to copy the contents of the list to an array explicitly. For example...

cimport cython
from libc.stdlib cimport malloc, free

...

def process(a, int len):

    cdef int *my_ints

    my_ints = <int *>malloc(len(a)*cython.sizeof(int))
    if my_ints is NULL:
        raise MemoryError()

    for i in xrange(len(a)):
        my_ints[i] = a[i]

    with nogil:
        #Once you convert all of your Python types to C types, then you can release the GIL and do the real work
        ...
        free(my_ints)

    #convert back to python return type
    return value
like image 82
Jeremy Brown Avatar answered Oct 18 '22 19:10

Jeremy Brown