Python列表来用Cython [英] Python list to Cython

查看:949
本文介绍了Python列表来用Cython的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何正常Python列表转换为C清单,用Cython,处理它,并返回一个Python列表。这样的:

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

Python脚本:

import mymodule

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

用Cython脚本(mymodule.pyd):

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

我读到MemoryView和许多其他的东西,但我没有真正unterstand什么发生,有很多例子都使用numpy的(我不想用我的脚本避免用户下载一个大包......反正我觉得它不与我的软件工作)。我需要一个非常简单的例子就明白了发生的事情完全一样。

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.

推荐答案

您需要将列表的内容明确复制到一个数组。例如...

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

这篇关于Python列表来用Cython的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆