包装C++,如何在cython中进行不同的类操作
wrapping C++, How to do different classes operation in cython
我正在尝试用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
相关文章:
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 重载操作程序时出错>>用于类中的字符串 memebr
- 对字符串进行位操作
- 我可以在 C++ 中的函数体之外进行操作吗?
- MPI突然停止了对多个核心的操作
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 对字符数组中的元素执行逐位操作
- 如何在directx/c++中进行平移/缩放操作
- 逐位操作的隐式类型转换
- 为什么一个向量上的多线程操作很慢
- 排序时无法执行交换操作.我做的时候它会崩溃.为什么
- 位移操作和位掩码未检测到重复字符
- 如何进行特定的位操作?
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 字符串操作 - 字符计数
- 此代码中的操作流程是什么?C/C++.
- 复制和交换习惯用法与移动操作之间的交互
- 像union_这样的 Boost.Geometry 操作如何处理浮点类型的基本不精确性?
- 为什么 std::lerp 不适用于任何已实现所需操作的类型?
- 无法合并生成操作.. 先决条件不同