这个问题在这里已经有了答案:
Passing C++ vector to Numpy through Cython without copying and taking care of memory management automatically
(2 个回答)
去年关闭。
有一个 C++ 函数返回浮点数 vector 。如何在不复制的情况下将此 vector 转换为 NumPy 数组?现在我这样做:
cdef np.ndarray arr = np.ascontiguousarray(cpp_vector, dtype=np.float)
return arr
但这在大 vector 上工作非常慢(假设发生复制)。
最佳答案
将 vector 转换为浮点数组并将其告诉 numpy 应该可以解决问题。
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)
[::1]
符号指的是 Typed MemoryView
( link )。在链接中,您将获得更多示例。我们也使用 np.asarray
将 tne MemoryView 变成一个 numpy 数组(在 SO Here 中回答)。这个想法是告诉 Cython 以预定义的格式查看该内存空间,避免任何复制。扩展自 this section名为 的文档强制使用 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
关于python - 在 Cython 中将 C++ vector 转换为 numpy 数组而无需复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59666307/