python - 在 Cython 中将 C++ vector 转换为 numpy 数组而无需复制

标签 python c++ cython numpy-ndarray

这个问题在这里已经有了答案:





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/

相关文章:

python - 使用cython性能下降

python - 如何使用 cython 编译和链接多个 python 模块(或包)?

python - 列表理解中的字符串格式

c++ - 来自 backtrace 的堆栈跟踪未显示在多线程环境下导致崩溃的方法

c++ - 使用 operator== 时 std::set 中 unique_ptr 的深度比较

C++11 等价于 boost shared_mutex

python-2.7 - 'pyximport' 在哪里?

python - 列表中最小元素到最大元素的距离(在列表内)

python - mobilenetv2 tflite 不是 python3 的预期输出大小

python - 未实现错误 : numpy() is only available when eager execution is enabled