我试图用cython包装一个c ++类,其中该类使用另一个类作为运算符重载的输入。我不知道如何在python部分中定义另一个类类型。我为每个类编写了pxd和pyx文件,并将Size 1导入Point。但是没能编译,。我在这里上传代码https://github.com/YuboHe/PointSize,有人看了一眼,给我一个提示,如何让操作工作,多多欣赏
这里有两个类,其中Point使用Size作为运算符重载的输入
在Point.h中
friend Point operator+(const Size& sz,const Point& pnt);
对应的pxd文件
cdef Point operator+(const Size& sz,const Point& pnt)
在python定义部分,我写的是这样的,但它总是给我一个错误can not convert object
def __add__(left,right):
cdef PyPoint pypt
cdef Point pt
if isinstance(left,PyPoint):
if isinstance(right,PyPoint):
pt = left.cpoint[0] + right.cpoint[0]
pypt = PyPoint(pt.x,pt.y)
return pypt
elif isinstance(right,PySize):
pt = left.cpoint[0] + right.csize[0]
pypt = PyPoint(pt.x,pt.y)
return pypt
答案 0 :(得分:0)
你需要告诉Cython你的对象是PyPoint
。使用类型转换执行此操作,即described in the documentation。
if isinstance(left,PyPoint):
if isinstance(right,PyPoint):
pt = (<PyPoint>left).cpoint[0] + (<PyPoint>right).cpoint[0]
或者,您可以跳过isinstance
并执行(<PyPoint?>left)
,如果类型不对,则会TypeError
。您可以捕获错误并尝试其他选项。
最后,您可以分配一个类型变量。同样,如果类型不匹配,则会抛出TypeError
:
cdef PyPoint right_pt
# ...
right_pt = right # catch the error if needed...
right_pt.cpoint[0] # is OK