简体   繁体   English

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

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

I am trying to wrap a c++ class with cython , where the class uses another class as input for operator overloading. 我试图用cython包装一个c ++类,其中该类使用另一个类作为运算符重载的输入。 I don't know how to define the another class type in the python part. 我不知道如何在python部分中定义另一个类类型。 I wrote both pxd and pyx file for each class, and imported the Size one into Point. 我为每个类都编写了pxd和pyx文件,并将Size 1导入Point。 But failed to compile,.I upload the codes here https://github.com/YuboHe/PointSize , Somebody plz give a glimpse and leave me a hint, how to make the operation work, Much appreciation 但无法编译,上传。我的代码在这里https://github.com/YuboHe/PointSize ,有人PLZ给一瞥,留下我一个提示,如何使运营工作,大部分升值

here are two classes, where Point uses Size as a input for operator overloading 这是两个类,其中Point使用Size作为操作符重载的输入

In Point.h 在Point.h

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

corresponding pxd file 对应的pxd文件

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

In the python definition part, I wrote like this, but it always gives me an error as can not convert object 在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

You need to tell Cython that your object is a PyPoint . 您需要告诉Cython您的对象是PyPoint Do this using a type cast, which is described in the documentation . 使用类型强制转换( 在文档中进行了描述)进行此操作

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

Alternatively you could skip the isinstance s and do (<PyPoint?>left) , which throws a TypeError if the type isn't right. 或者,您可以跳过isinstance并执行(<PyPoint?>left) ,如果类型不正确,则会抛出TypeError You'd catch the error and try other options. 您会发现错误并尝试其他选择。

Finally you can assign to a typed variable. 最后,您可以分配给类型变量。 Again, this throws a TypeError if the types don't match: 同样,如果类型不匹配,则会抛出TypeError

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM