【问题标题】:How do I convert Cython array to Python object so I can return the result?如何将 Cython 数组转换为 Python 对象以便返回结果?
【发布时间】:2017-06-19 21:16:30
【问题描述】:

我很惊讶没有关于将 Cython 数组转换为 Python 对象的文档。任何建议将不胜感激。

# Values are a list of integers containing numerators and denominators 
def test_looping_ndarray_nd_list(list matrix):   

    cdef int *my_ints
    cdef i

    # Allocate memory to store ctype integers in memory 
    my_ints = <int *>malloc(len(matrix)*cython.sizeof(int)) 
    if my_ints is NULL:
        raise MemoryError() 

    for i in xrange(len(matrix)): # Convert to ctypes
        my_ints[i] = matrix[i]

    # How do I convert my_ints to Python object so I can return the result???

    return 

【问题讨论】:

  • 我回答了您的问题,但没有足够的上下文来理解您为什么要为此使用指针数组和 malloc。如果我的回答对你不起作用,请告诉我。顺便说一句,如果你 确实 以某种方式将 malloc 分配的内存返回给 python,它永远不会被释放,所以你会造成内存泄漏。
  • 其实我详细说一下
  • @MLhacker 我怀疑你没有抓住重点,使用 numpy 数组(具有适当的 dtype)和 memoryview(正如 Nathan12343 建议的那样)会好得多。但是,请参阅 this recent question/answer 以获取有关如何执行您所要求的操作的指导。

标签: python cython


【解决方案1】:

我会使用类型化的内存视图来做到这一点:

import numpy as np
cimport numpy as np
cimport cython

# Values are a list of integers containing numerators and denominators
@cython.boundscheck(False)
def test_looping_ndarray_nd_list(list matrix):   

    cdef np.intp_t[:] my_ints
    cdef int i

    # Allocate memory to store ctype integers in memory 
    my_ints = np.array(matrix, dtype='int')

    # do some work while releasing the GIL
    with nogil:
        for i in range(my_ints.shape[0]):
            my_ints[i] = 2*my_ints[i]

    return np.asarray(my_ints).tolist()

【讨论】:

  • 其实,让我详细说明一下。本质上。我有一个未知大小的 Python 列表传递给函数。最终我想操纵列表的每个元素并应用 nogil。但是,首先我需要在 Ctypes 中创建一个数组,这就是为什么我使用指针和 malloc 来实现我的目标。
  • 为什么不只遍历列表?
  • 哦,我明白了,因为你不能遍历 nogil 块中的列表。我仍然建议将您的数组转换为类型化的内存视图(可以在 nogil 块中迭代)。我已经修改了我的答案,让我知道这是否适合你。
  • nathan,第一个 cdef int 声明旁边的 [:] 的目的是什么?
  • 我已经更新了我的答案,使其更便携。 np.intp_t 是“特定于平台的 int”的缩写。我认为这将解决您遇到的错误。为了回答您的第一个问题,[:] 语法声明了一维类型的内存视图:cython.readthedocs.io/en/latest/src/userguide/memoryviews.html
猜你喜欢
  • 1970-01-01
  • 2012-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-25
  • 2013-06-05
相关资源
最近更新 更多