gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:53:29 25 4
gpt4 key购买 nike

我正在尝试包装一个使用共享指针和非常简单的继承的简单 C++ 类。我有一个类 Point 是一个基类,而 SphericalPoint 是它的子类。我有一个点的共享指针向量。我希望向量将子类对象保存在其中,即球形点。 Point 的子类可以有很多个,Spherical Point 在这里仅作表示。当我这样做时,我得到以下编译错误 -

 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 时,我得到了一大堆其他错误。在以下链接 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);
};

这是我的 point.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)

还有我的 point.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)

更新

我只是将子类的实例化移到它自己的单独方法中,因为它实际上不是 的一部分初始化 .但我仍然得到相同的编译错误。我还想知道子类 SphericalPoint 的实例化是否是问题的原因,即
  point = shared_ptr[Point](new SphericalPoint())

这是推荐的方式吗?

最佳答案

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

相反,您应该使用 cython.operator.dereference .

from cython.operator cimport dereference

# ...

dereference(point).setCoordinate1(instance)

关于python - 简单继承的 Cython 编译错误 - 对象没有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55919597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com