【问题标题】:Cython wrapping operator<< from multiple namespaces来自多个命名空间的 Cython 包装运算符<<
【发布时间】:2014-03-23 01:15:10
【问题描述】:

如何在 Cython 中包装运算符 >> 重载?

//LIB.h
namespace LIB
{
    class Point
    {
        friend std::istream &operator >> (std::istream &in, Point &pt)
        bool operator == (const Point &pos) const
        ...
    }
}

已经有一个命名空间声明了namespace "LIB":,那我该如何处理std::命名空间呢?

#LIB.pxd
cdef extern from "LIB.h" namespace "LIB":
    cdef cppclass Point:
        #friend std::istream &operator >> (std::istream &in, Point &pt)
        bint operator == (const Point &pos) const
        ...

Here it explains 多个 cdef extern 块是可能的,但我不知道这将如何工作,因为我无法重新定义类。

【问题讨论】:

  • 命名空间问题一点都不清楚。在 .h 文件 (LIB.h ?) 中,是否在命名空间 LIB 中声明了运算符? std:: 在这里的作用是什么? '已经声明了一个命名空间'是什么意思?
  • 为更清晰而编辑。我不确定如何处理第二个 std:: 命名空间。 cython 文档中的所有示例都在同一个命名空间中包含所有包装函数。
  • 我在我的答案中实施了您的编辑建议,但我也删除了指向您的问题的所有模板参数,因为它们没有多大意义并且与问题完全无关。

标签: c++ wrapper iostream cython friend


【解决方案1】:

我认为最简单的解决方案是向 Cython 假装operator&lt;&lt;std::istream 忘记朋友的方法。然后,C++ 编译器将整理出这些部分。所以这似乎是一个可行的解决方案(它可以编译,但我没有一路测试它):

这是我的LIB.h 打包文件:

#include <iostream>
namespace LIB {
    class Point {
        friend std::istream &operator << (std::istream &in, Point);
    };
}

Cython 包装器应该如下:

cdef extern from "LIB.h" namespace "LIB":
    cdef cppclass Point:
        pass

cdef extern from "<iostream>" namespace "std":
    cdef cppclass istream:
        istream &operator << (Point)

    istream cin

然后编译器接受以下文件:

cimport lib

def foo():
    cdef lib.Point bla

    lib.cin << bla

仅供参考,我编译时使用:

cython --cplus bla.pyx                  
g++ `python-config --cflags` bla.cpp -c

【讨论】:

  • 谢谢!我没有意识到可以在同一个 .pxd 中启动多个 cdef extern 并使用它们来处理多个命名空间。
猜你喜欢
  • 2019-08-26
  • 1970-01-01
  • 1970-01-01
  • 2011-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-03
相关资源
最近更新 更多