Cython封装多个命名空间中的operator<<

4

我该如何在Cython中重载运算符 >> ?

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

已经声明了一个命名空间 "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
        ...

这里解释了多个cdef extern块是可能的,但我不明白它是如何工作的,因为我不能重新定义类。


命名空间问题并不清楚。在头文件(LIB.h?)中,运算符是否在命名空间LIB中声明?这里的std::的作用是什么?“已经声明了一个命名空间”是什么意思? - hivert
我不确定如何处理第二个 std:: 命名空间。Cython 文档中的所有示例都将所有包装函数放在同一个命名空间中。 - ratiotile
我已经实现了你对我的答案的编辑建议,但我也删除了所有模板参数,以便指向你的问题,因为它们并没有太多意义,而且与问题完全无关。 - hivert
1个回答

6
我认为最简单的解决方法是让Cython假装operator<<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 并使用它们来处理多个命名空间是可能的。 - ratiotile

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接