Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

arrays - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...