包装C++,如何在cython中进行不同的类操作

wrapping C++, How to do different classes operation in cython

本文关键字:操作 C++ cython 包装      更新时间:2023-10-16

我正在尝试用cython包装一个c ++类,其中该类使用另一个类作为运算符重载的输入。我不知道如何在 python 部分中定义另一个类类型。我为每个类编写了 pxd 和 pyx 文件,并将大小导入到 Point 中。但编译失败,。我在这里上传代码 https://github.com/YuboHe/PointSize,有人请瞥一眼,给我一个提示,如何使操作工作,非常感谢

下面是两个类,其中 Point 使用 Size 作为运算符重载的输入

在点.h

friend Point operator+(const Size& sz,const Point& pnt);  

对应的 PXD 文件

cdef Point operator+(const Size& sz,const Point& pnt)

在python定义部分,我是这样写的,但它总是给我一个错误,因为无法转换对象

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

你需要告诉Cython你的对象是一个PyPoint。使用类型转换执行此操作,如文档中所述。

if isinstance(left,PyPoint):
    if isinstance(right,PyPoint):
         pt = (<PyPoint>left).cpoint[0] + (<PyPoint>right).cpoint[0]

或者,您可以跳过 isinstance s 并执行 (<PyPoint?>left) ,如果类型不正确,则会抛出TypeError。您会发现错误并尝试其他选项。

最后,您可以赋值给类型化变量。同样,如果类型不匹配,这将引发TypeError

cdef PyPoint right_pt
# ...
right_pt = right # catch the error if needed...
right_pt.cpoint[0] # is OK