来自多个命名空间的 Cython 包装运算符<<

Cython wrapping operator<< from multiple namespaces

本文关键字:lt 包装 运算符 Cython 命名空间      更新时间:2023-10-16

如何在Cython中包装操作符>> overload ?

//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
        ...

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

我认为最简单的解决方案是假装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