【问题标题】:non-member operator in CythonCython 中的非会员操作员
【发布时间】:2015-04-19 16:25:25
【问题描述】:

我目前正在为现有的 C++ 库做一个 Cython 包装器。我在 C++ 中有一个重载的非成员运算符,例如

Data operator+(Data const& a, Data const& b)

在描述标题的pxd文件中,我写道

cdef extern from 'blabla.h':
    Data operator+(const Data&, const Data&)

现在我如何在另一个pyx 文件中使用这个operator+

【问题讨论】:

  • include "your_pxd.pxd" 在您的 .pyx 中不起作用?
  • @CristiánAntuña 好吧,我必须将此运算符重命名为其他名称并将其称为普通函数。我想改用+

标签: cython


【解决方案1】:

对于非常简单的情况,例如在您的示例中,您可以对 Cython 撒谎并告诉它运算符是成员函数:

cdef extern from 'blabla.h':
  cdef cppclass Data:
    # the rest of the data definitions
    Data operator+(const Data&)

它只使用此信息知道它可以将代码a+b(其中ab 是数据对象)转换为__pyx_v_a + __pyx_v_b,然后让c++ 编译器完成其余的工作(它知道如何因为从“blabla.h”导入)。因此,会员和非会员之间的区别是无关紧要的。

然而:使用非成员运算符的主要原因之一是允许类似

Data operator+(int a, const Data& b);

你可以完成这项工作,但它有点混乱。在你的 pxd 文件中做

cdef extern from 'blabla.h':
    Data operator+(int, const Data&) # i.e. do nothing special

在你的 pyx 文件中

from my_pxd_file import * # works fine
## but this isn't accepted unfortunately:
from my_pxd_file import operator+

如果您想避免在执行import * 时造成过多的命名空间污染,您可以创建一个仅包含运算符而不包含类定义的 pxd 文件(虽然我还没有测试过)

总结 - 两种方法取决于您的用例有多复杂......

【讨论】:

    猜你喜欢
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    • 2017-12-22
    • 1970-01-01
    • 2010-11-25
    • 2015-07-25
    • 2011-05-10
    • 1970-01-01
    相关资源
    最近更新 更多