问题
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