Convert C++ vector to numpy array in Cython without copying [duplicate]

雨燕双飞 提交于 2021-01-27 04:45:49

问题


There is a C++ function that returns a vector of floats. How to convert this vector to NumPy array without copying? Now I'm doing this:

cdef np.ndarray arr = np.ascontiguousarray(cpp_vector, dtype=np.float)
return arr

but this works very slow (assume copying occurs) on large vectors.


回答1:


Casting the vector to float array and telling it to numpy should do the trick.

cdef float[::1] arr = <float [:cpp_vector.size()]>cpp_vector.data()
return arr

# arr is of type Memoryview. To cast into Numpy:
np_arr = np.asarray(arr)

The [::1] notation refers to a Typed MemoryView (link). In the link you'll get more examples. We also use np.asarray to turn tne MemoryView into a numpy array (answered in SO Here). The idea is to tell Cython to look at that memory space with a predefined format, avoiding any copying. Expanding from this section of the docs named Coertion to Numpy:

Memoryview (and array) objects can be coerced to a NumPy ndarray, without having to copy the data. You can e.g. do:

cimport numpy as np
import numpy as np

numpy_array = np.asarray(<np.float_t[:10, :10]> my_pointer)

Of course, you are not restricted to using NumPy’s type (such as np.float_ here), you can use any usable type.

Source: https://cython.readthedocs.io/en/latest/src/userguide/memoryviews.html#coercion-to-numpy



来源:https://stackoverflow.com/questions/59666307/convert-c-vector-to-numpy-array-in-cython-without-copying

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!