在.pxd文件中,我写了
_Point operator+(const _Point other) const
_Point operator -(const _Point other) const
bool operator==(const _Point other) const
在.pyx文件中,我写了
def __eq__(self, Point other):
cdef _Point* selfptr = self.c_point.get()
cdef _Point* otherptr = other.c_point.get()
return selfptr[0] == otherptr[0]
但是对于像
__add__
这样的运营商来说,我不能像==
那样做同样的事情。
def __add__(self, Point other):
cdef _Point * selfptr = self.c_point.get()
cdef _Point * otherptr = other.c_point.get()
return selfptr[0] + otherptr[0]
错误信息
× python setup.py egg_info did not run successfully.
│ exit code: 1
╰─> [27 lines of output]
Error compiling Cython file:
------------------------------------------------------------
...
return not self.__eq__(other)
def __add__(self, Point other):
cdef _Point * selfptr = self.c_point.get()
cdef _Point * otherptr = other.c_point.get()
return selfptr[0] + otherptr[0]
^
------------------------------------------------------------
src/Geometry/Point/Point.pyx:170:26: Cannot convert '_Point' to Python object
我该如何解决这个问题?谢谢你
错误只是指出返回的
_Point
不是Python对象,你必须将其包装在Python对象中,一种方法是构造另一个PyPoint并替换其指针。
%%cython -c=-std=c++20 --cplus -a
cdef extern from *:
"""
class Value
{
public:
int m_val;
Value(): m_val(0) {}
Value(int val): m_val(val) {}
Value operator+(const Value& other) const { return m_val + other.m_val;}
};
"""
cdef cppclass Value:
Value() noexcept
Value(int) noexcept
Value operator+(const Value&) const
Value(Value) noexcept
cdef class PyValue:
cdef Value* val
def __init__(self):
val = new Value(0)
def __add__(self, PyValue other):
ret_val = PyValue()
del ret_val.val
ret_val.val = new Value(self.val[0] + other.val[0])
return ret_val