简单继承对象没有属性的Cython编译错误

2024-09-27 17:56:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图包装一个简单的C++类,它使用共享指针和非常简单的继承。我有一个类点,它是基类,而SphericalPoint是它的子类。我有一个点的共享指针向量。我希望向量包含子类对象,即球面点。可以有许多子类的点和球面点只显示在这里表示。当我这样做的时候,我得到以下编译错误-

 point.pyx:18:13: Object of type 'shared_ptr[Point]' has no attribute 'setCoordinate1'

Error compiling Cython file:

    point = shared_ptr[Point](new SphericalPoint())
    cdef double latitude, longitude
    latitude = 0.
    longitude = 0.
    point.setCoordinate1(latitude)
    point.setCoordinate2(longitude)


  point.pyx:19:13: Object of type 'shared_ptr[Point]' has no attribute 'setCoordinate2'

最初,当我在谷歌上搜索这个时,我认为问题的原因可能是因为我在Cython代码中没有关键字public,但是当我添加关键字public时,我会得到一大堆其他错误。在下面的链接Wrapping C++ with Cython中,没有在.pxd文件中显示public的示例。你知道吗

这是一个重现问题的MVCE。如何修复此错误?Cython版本是0.29.7

h点

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

class SphericalPoint : public Point
   {
     private:
         double longitude,latitude;
     public:
         double getCoordinate1();
         double getCoordinate2();
         void   setCoordinate1(double latitude);
         void   setCoordinate2(double longitude);
    };

这是我的点.pxd文件

cdef extern from "Point.h":
    cdef cppclass Point:
       Point() except +
       double getCoordinate1()
       double getCoordinate2()
       void setCoordinate1(double coordinate1)
       void setCoordinate2(double coordinate2)

   cdef cppclass SphericalPoint(Point):
      SphericalPoint() except +
      double getCoordinate1()
      double getCoordinate2()
      void setCoordinate1(double coordinate1)
      void setCoordinate2(double coordinate2)

还有我的点.pyx文件

 from libcpp.memory cimport shared_ptr
 from libcpp.vector cimport vector

 from point cimport Point

 cdef class PyA:

     cdef vector[shared_ptr[Point]]* points

     def __cinit__(self):
        self.points = new vector[shared_ptr[Point]]()

     def buildPoints(self):

        cdef shared_ptr[Point] point
        point = shared_ptr[Point](new SphericalPoint())
        cdef double latitude, longitude
        point.setCoordinate1(latitude)
        point.setCoordinate2(longitude)

更新

我只是将子类的实例化移到它自己的独立方法中,因为它实际上不是cinit的一部分。但我还是会遇到同样的编译错误。我还想知道子类spherecalpoint的实例化是否是问题的原因

  point = shared_ptr[Point](new SphericalPoint())

这是推荐的方式吗?你知道吗


Tags: 错误public子类pointshareddoublelatitudecdef
1条回答
网友
1楼 · 发布于 2024-09-27 17:56:18

Cython可以为常规指针类型解决这个问题,并使用->生成c++代码,但是对于实现带有运算符重载的指针接口的类型,它无法解决这个问题。你知道吗

相反,您应该使用^{}。你知道吗

from cython.operator cimport dereference

# ...

dereference(point).setCoordinate1(instance)

相关问题 更多 >

    热门问题