【发布时间】: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 以获取有关如何执行您所要求的操作的指导。