gpt4 book ai didi

Python 列表到 Cython

转载 作者:太空狗 更新时间:2023-10-29 17:15:44 25 4
gpt4 key购买 nike

我想知道如何使用 Cython 将普通 python 列表转换为 C 列表,处理它并返回一个 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(我不想使用它来避免我的脚本的用户下载一个大包......无论如何我认为它不适用于我的软件)。我需要一个非常简单的示例来准确理解正在发生的事情。

最佳答案

您需要将列表的内容显式复制到数组中。例如……

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,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14780007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com