代码之家  ›  专栏  ›  技术社区  ›  Greg

如何将C++向量转换成Cython中的一个数字向量,同时最小化Python解释器交互?

  •  1
  • Greg  · 技术社区  · 7 年前

    • 如何提供 numpy.ndarray 作为函数输出数据类型和
    • cimport numpy 而不是 import numpy 创建一个没有Python开销的数组?

    以下代码适用于 努比·恩达雷 cdef numpy.ndarray array(int start, int end): . 根据注释,它仍然有很多Python开销(不包括 range(start, end) C++向量的初始化。

    %%cython -a
    # distutils: language = c++
    
    import numpy
    from libcpp.vector cimport vector
    
    
    cdef numpy.ndarray array(int start, int end):
        cdef vector[int] vect = range(start, end)
        return numpy.array(vect)
    
    print(array(1,15))
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Pierre de Buyl    7 年前

    NumPy数组是Python对象。如果希望在编译级别使用它们,则应使用 memoryviews 是由赛顿支持的。然后您可以要求 np.asarray(cython_memoryview_variable) 去Python。