Cython封装含显式默认==运算符的C++结构体的疑问
问题解答
为什么未声明运算符重载仍能编译成功?
Cython的cdef struct本质是直接映射到C/C底层结构体。你在C代码里已经显式默认了operator==,即使Cython代码里没写重载声明,底层的C++结构体依然自带这个比较逻辑。编译时Cython会直接复用底层结构体的定义,因此不会报错,且你在Cython的C层代码中其实已经可以直接使用==进行比较。
如何在Cython中显式实现/绑定==运算符?
根据使用场景,有两种处理方式:
方式1:绑定外部C++结构体的operator==
如果是直接封装已有的C++结构体,只需在cdef extern块中声明该运算符,就能在Cython代码中直接调用:
cdef extern from "your_struct_header.h": cdef cppclass myStruct: float a float b float c float d bool operator==(const myStruct&) const = default # 直接使用示例 cdef myStruct s1, s2 s1.a = 1.0 s2.a = 1.0 print(s1 == s2)
方式2:在纯Cython结构体中实现比较逻辑
如果是定义Cython原生的cdef struct,可以通过__richcmp__方法实现==和!=:
cdef struct myStruct: np.float32_t a np.float32_t b np.float32_t c np.float32_t d cdef inline bint __richcmp__(myStruct other, int op): if op == 2: # Py_EQ,对应== return (self.a == other.a and self.b == other.b and self.c == other.c and self.d == other.d) elif op == 3: # Py_NE,对应!= return not self.__richcmp__(other, 2) return False
额外说明
- 若仅在Cython的C层代码中使用结构体比较,无需额外声明也能直接用
==,因为Cython会生成对应C++代码调用底层默认运算符。 - 若要让Python层代码能直接比较该结构体对象,需要将结构体包装为Python扩展类型,并通过
__richcmp__间接实现Python的__eq__方法。
内容的提问来源于stack exchange,提问作者devOrange
相关产品推荐
相关产品推荐

