在Cython中使用move方法时出现编译错误

Compilation error when using the move method in Cython

我的问题与此处提出的问题类似 - 我也遇到了分段错误,但在我修复它之前,我遇到了一些编译错误,需要使用 Cython 中的 move 方法解决。

这是我最简单的例子(只是对网上提供的矩形例子的扩展

我想做什么 我的 C++ 代码 return 是点的双端队列。它也可以 return 点向量。任何容器都可以

在 cython 代码中,我想将点的 returned 双端队列(for 循环的每次迭代一个)存储在集合(例如向量或双端队列)中。这个集合将是一个实例变量。

稍后我想遍历集合并将点的双端队列转换为 python 列表列表。这是我认为出现分段错误的地方。

Point.h

#ifndef POINT_H
#define POINT_H

class  Point
{
  private:
  double coordinate1,coordinate2;
  public:
   virtual double  getCoordinate1() const;
   virtual double  getCoordinate2() const ;
   virtual void    setCoordinate1(double coordinate1);
  virtual void    setCoordinate2(double coordinate2);
 };

Rectangle.h

   #include <deque>
   #include "Point.h"
   using std:deque;

   deque<Point> getAllPoints(Point query);

Rectangle.cpp

    include "Rectangle.h"

     deque<Point> Rectangle::getAllPoints(Point query)
     {
      deque<Point> deq;
        for (int i = 0;i < 10000; ++i)
         {
           deq.push_back(query);
         }
      return deq;

注意 与链接问题不同,我不是 return 一个地址而是 return 一个参考

rect.pxd

 cdef extern from "<utility>" namespace "std" nogil:
   T move[T](T) #
 cdef extern from "Point.h":
   cdef cppclass Point:
   Point() nogil except +
   double getCoordinate1()
   double getCoordinate2()
   void setCoordinate1(double coordinate1) nogil
   void setCoordinate2(double coordinate2) nogil

cdef cppclass SphericalPoint(Point):
   SphericalPoint() nogil except +
   double getCoordinate1()
   double getCoordinate2()
   void setCoordinate1(double lat) nogil
   void setCoordinate2(double lon) nogil

cdef extern from "Rectangle.h" namespace "shapes":
   cdef cppclass Rectangle:
     Rectangle(int, int, int, int) except + nogil
     deque[Point] getArea(Point p) nogil

最后

rect.pyx

 cdef class PyRectangle:
   cdef Rectangle *rect    
   cdef deque[Point] colOfPoints

   def __cinit__(self, int x0, int y0, int x1, int y1):
    self.rect = new Rectangle(x0, y0, x1, y1)
    self.colOfPoints = deque[Point]()

 def performCalc(self,maxDistance,chunk):
    cdef deque[Point] area
    cdef double[:,:] gPoints
    gPoints = memoryview(chunk)
    for i in range(0,len(gPoints)):
        with nogil:
            area =  self.getArea(gPoints[i])
            self.colOfPoints = move(area)

cdef deque[Point] getArea(self,double[:] p) nogil:
    cdef deque[Point] area
    area = self.rect.getArea(point)
    return area

我相信我在 setup.pyx

中设置了 C++ 17

setup.py

  os.environ['CFLAGS'] = '-O3 -Wall -std=c++17'

  ext_modules = [Extension("rect",
                     ["rect.pyx","Rectangle.cpp"],
                     include_dirs=['/usr/local/include'],
                     extra_link_args=["-std=c++17"],
                     language='c++',
                 )]

extensions = cythonize(ext_modules, language_level = "3")

我遇到了这些编译错误

 rect.cpp: In function ‘PyObject*   __pyx_pf_4rect_11PyRectangle_6performCalc(__pyx_obj_4rect_PyRectangle*, PyObject*, PyObject*)’:
 rect.cpp:3781:81: error: no matching function for call to ‘move<std::deque<Point, std::allocator<Point> > >(std::deque<Point>&)’
       __pyx_v_self->colOfPoints = std::move<std::deque<Point> >(__pyx_v_area);
                                                                             ^
     In file included from /usr/include/c++/7 /bits/nested_exception.h:40:0,
             from /usr/include/c++/7/exception:143,
             from /usr/include/c++/7/ios:39,
             from rect.cpp:632:
   /usr/include/c++/7/bits/move.h:98:5: note: candidate: template<class _Tp> constexpr typename std::remove_reference< <template-parameter-1-1> >::type&& std::move(_Tp&&)
 move(_Tp&& __t) noexcept
 ^~~~
 /usr/include/c++/7/bits/move.h:98:5: note:   template argument deduction/substitution failed:
  rect.cpp:3781:81: note:   cannot convert ‘__pyx_v_area’ (type ‘std::deque<Point>’) to type ‘std::deque<Point>&&’
       __pyx_v_self->colOfPoints = std::move<std::deque<Point> >(__pyx_v_area);
                                                                             ^
 In file included from /usr/include/c++/7/bits/char_traits.h:39:0,
             from /usr/include/c++/7/ios:40,
             from rect.cpp:632:
 /usr/include/c++/7/bits/stl_algobase.h:479:5: note: candidate: template<class _II, class _OI> _OI std::move(_II, _II, _OI)
 move(_II __first, _II __last, _OI __result)
 ^~~~
 /usr/include/c++/7/bits/stl_algobase.h:479:5: note:   template argument deduction/substitution failed:
    rect.cpp:3781:81: note:   candidate expects 3 arguments, 1 provided
       __pyx_v_self->colOfPoints = std::move<std::deque<Point> >(__pyx_v_area);
                                                                                    ^
   In file included from /usr/include/c++/7/deque:66:0,
             from rect.cpp:636:
   /usr/include/c++/7/bits/deque.tcc:1048:5: note: candidate: template<class _Tp> std::_Deque_iterator<_Tp, _Tp&, _Tp*> std::move(std::_Deque_iterator<_Tp, const _Tp&, const _Tp*>, std::_Deque_iterator<_Tp, const _Tp&, const _Tp*>, std::_Deque_iterator<_Tp, _Tp&, _Tp*>)
 move(_Deque_iterator<_Tp, const _Tp&, const _Tp*> __first,
 ^~~~
   /usr/include/c++/7/bits/deque.tcc:1048:5: note:   template argument deduction/substitution failed:
  rect.cpp:3781:81: note:   candidate expects 3 arguments, 1 provided
       __pyx_v_self->colOfPoints = std::move<std::deque<Point> >(__pyx_v_area);
                                                                             ^
   In file included from /usr/include/c++/7/deque:64:0,
             from rect.cpp:636:
  /usr/include/c++/7/bits/stl_deque.h:424:5: note: candidate: template<class _Tp> std::_Deque_iterator<_Tp, _Tp&, _Tp*> std::move(std::_Deque_iterator<_Tp, _Tp&, _Tp*>, std::_Deque_iterator<_Tp, _Tp&, _Tp*>, std::_Deque_iterator<_Tp, _Tp&, _Tp*>)
 move(_Deque_iterator<_Tp, _Tp&, _Tp*> __first,
 ^~~~
  /usr/include/c++/7/bits/stl_deque.h:424:5: note:   template argument deduction/substitution failed:
  rect.cpp:3781:81: note:   candidate expects 3 arguments, 1 provided
       __pyx_v_self->colOfPoints = std::move<std::deque<Point> >(__pyx_v_area);

下面是我用来重现您的问题的稍微简化的版本。我只是将它作为如何进一步简化示例的说明 - 请注意,我不需要使用 C++ 文件 - 我可以通过将代码放入 docstring 来将代码直接包含在 pyx 文件中。

#distutils: language = c++

from libcpp.deque cimport deque

cdef extern from *:
    """
    #include <deque>
    using std::deque;

    class Point{};

    deque<Point> getAllPoints() {
        deque<Point> deq;
        for (int i=0; i<10000; ++i) {
            deq.push_back(Point{});
        }
        return deq;
    }

    """
    cdef cppclass Point:
        pass
    deque[Point] getAllPoints()

cdef extern from "<utility>" namespace "std" nogil:
    T move[T](T)

cdef class PyRectange:
    cdef deque[Point] colOfPoints

    def something(self):
        cdef deque[Point] area = self.getArea()
        self.colOfPoints = move(area)

    cdef deque[Point] getArea(self):
        return getAllPoints()

基本问题是,当 Cython 为模板生成 C++ 代码时,它会编写 std::move<deque<Point>>(area) 而不是 std::move(area) 并让 C++ 推断模板类型。由于我不完全理解的原因,这似乎很多时候都会生成错误的代码。

我有两个半解:

  1. 不要告诉 Cython move 是模板函数。而只是告诉它你想要的重载:

    cdef extern from "<utility>" namespace "std" nogil:
        deque[Point] move(deque[Point])
    

    这是我认为最简单的方法,可能也是我的方法。

  2. 如果您避免创建临时文件 area,那么 C++ 代码可以使用模板:

    self.colOfPoints = move(self.getArea())
    

    我怀疑在这种情况下您甚至可能不需要 move - C++ 可能无论如何都会自动使用移动赋值运算符。

  3. This answer 声称想出了一个小包装器帮助 Cython 调用正确的 move (它也略微错过了它正在回答的问题的实际问题...... ).我自己还没有测试过,但如果你想要一个模板化的移动,它可能值得一试。