Jea*_*ant 15 python arrays cython
我想知道如何使用Cython将普通的python列表转换为C列表,处理它并返回一个python列表.喜欢:
Python脚本:
import mymodule
a = [1,2,3,4,5,6]
len = len(a)
print(mymodule.process(a,len))
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
我读到了关于MemoryView和许多其他的东西,但我并不是真的知道发生了什么,很多例子使用Numpy(我不想用它来避免我的脚本用户下载一个大包...反正我觉得它不是'使用我的软件).我需要一个非常简单的例子来了解究竟发生了什么.
Jer*_*own 22
您需要明确地将列表的内容复制到数组中.例如...
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14320 次 |
| 最近记录: |