Python 列表转 Cython

18 投票
1 回答
19695 浏览
提问于 2025-04-17 15:17

我想知道怎么把普通的Python列表转换成C语言的列表,用Cython处理后再返回一个Python列表。比如:

Python脚本:

import mymodule

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

Cython脚本(mymodule.pyd):

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

我读过关于MemoryView和其他很多东西,但我其实不太明白发生了什么,而且很多例子都用到了Numpy(我不想用这个,因为这样用户就得下载一个很大的包……总之,我觉得这和我的软件不兼容)。我需要一个非常简单的例子,来理解到底发生了什么。

1 个回答

25

你需要把列表里的内容明确地复制到一个数组里。比如说...

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

撰写回答