问题描述
在cython中,如何创建具有已定义属性的ndarray对象而不为其内容分配内存?
In cython, how do I create an ndarray object with defined properties without allocating memory for its contents?
我的问题是我想调用一个需要ndarray但我的数据在纯c数组中的函数.由于某些限制,我无法直接使用ndarray.
My problem is that I want to call a function that requires a ndarray but my data is in a pure c array. Due to some restrictions I cannot switch to using an ndarray directly.
代码段以说明我的意图:
Code-segement to illustrate my intention:
cdef:
ndarray[npy_uint64] tmp_buffer
uint64_t * my_buffer
tmp_buffer = np.empty(my_buffer_size, dtype='uint64')
my_buffer = <uint64_t *> malloc(my_buffer_size * sizeof(uint64_t))
(... do something with my_buffer that cannot be done with a ndarray ...)
tmp_buffer.data = my_buffer
some_func(tmp_buffer)
这似乎效率低下,因为为tmp_buffer
分配了内存并将其填充为零,这将永远不会使用.如何避免这种情况?
This seems inefficient since for tmp_buffer
memory is allocated and zero-filled which will never be used. How do I avoid this?
推荐答案
除了效率,这种分配是否可以编译?
Efficiency aside, does this sort of assignment compile?
np.empty
不为零填充. np.zeros
可以做到这一点,甚至可以即时"完成.
np.empty
does not zero fill. np.zeros
does that, and even that is done 'on the fly'.
为什么numpy.zeros和numpy.zeros_like之间的性能差异?探索empty
,zeros
和已实施.
Why the performance difference between numpy.zeros and numpy.zeros_like? explores how empty
, zeros
and zeros_like
are implemented.
我只是cython
的初学者,但我必须使用:
I'm just a beginner with cython
, but I have to use:
tmp_buffer.data = <char *>my_buffer
以另一种方式,将my_buffer
分配为tmp_buffer
的data
,又如何呢?
How about going the other way, making my_buffer
the allocated data
of tmp_buffer
?
array1 = np.empty(bsize, dtype=int)
cdef int *data
data = <int *> array1.data
for i in range(bsize):
data[i] = bsize-data[i]
http://gael-varoquaux.info/programming/cython-example-of-exposed-c-computed-arrays-in-python-without-data-copies.html 建议使用np.PyArray_SimpleNewFromData
从现有数据缓冲区创建数组.
http://gael-varoquaux.info/programming/cython-example-of-exposing-c-computed-arrays-in-python-without-data-copies.htmlsuggests using np.PyArray_SimpleNewFromData
to create an array from an existing data buffer.
关于内存视图 http://docs.cython.org/src/userguide/memoryviews.html
这篇关于cython:创建ndarray对象而不为数据分配内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!