Cython:使用C++流

pio*_*ocz 10 c++ python io stream cython

问题

如何使用Cython中的c ++流(如std::ifstreamostream)?在c ++中,您可以执行以下操作:

std::ofstream output { filename, std::ios::binary };
output.write(...);
Run Code Online (Sandbox Code Playgroud)

你如何在Cython中实现同样的目标?

当前状态

我已经在Cython中包装了fstream中的结构,以便我可以在函数声明中使用它们的名称,但是棘手的部分是使用(在Cython中包装,可能)write方法并创建流.我没有在互联网上找到任何代码示例.

PS我知道一个可能的答案是只使用Python的IO但我需要传递/返回与我正在连接的C++代码的流.

这是包装流声明的代码:

cdef extern from "<iostream>" namespace "std":
    cdef cppclass basic_istream[T]:
        pass

    cdef cppclass basic_ostream[T]:
        pass

    ctypedef basic_istream[char] istream

    ctypedef basic_ostream[char] ostream
Run Code Online (Sandbox Code Playgroud)

Dav*_*idW 6

与包装任何其他C++类相比,c ++ iostream没有太多特别之处.唯一棘手的一点是获取访问权限std::ios_base::binary,我通过告诉Cython这std::ios_base是一个命名空间而不是一个类来做到这一点.

# distutils: language = c++

cdef extern from "<iostream>" namespace "std":
    cdef cppclass ostream:
        ostream& write(const char*, int) except +

# obviously std::ios_base isn't a namespace, but this lets
# Cython generate the correct C++ code
cdef extern from "<iostream>" namespace "std::ios_base":
    cdef cppclass open_mode:
        pass
    cdef open_mode binary
    # you can define other constants as needed

cdef extern from "<fstream>" namespace "std":
    cdef cppclass ofstream(ostream):
        # constructors
        ofstream(const char*) except +
        ofstream(const char*, open_mode) except+

def test_ofstream(str s):
    cdef ofstream* outputter
    # use try ... finally to ensure destructor is called
    outputter = new ofstream("output.txt",binary)
    try:
        outputter.write(s,len(s))
    finally:
        del outputter
Run Code Online (Sandbox Code Playgroud)

另外要补充的是,我没有对完全模板化的类层次结构感到烦恼 - 如果你也想要这些wchar变体可能会有用,但是只告诉Cython你实际使用的类是多么容易.