python - Cython:使用 C++ 流

标签 python c++ io stream cython

问题

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

std::ofstream output { filename, std::ios::binary };
output.write(...);

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

当前状态

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

附言 我知道一个可能的答案是只使用 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

最佳答案

与包装任何其他 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

要补充的另一件事是,我没有为完整的模板化类层次结构而烦恼——如果您还想要 wchar 变体,这可能会有用,但只告诉 Cython 更容易您实际使用的类。

关于python - Cython:使用 C++ 流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30984078/

相关文章:

c++ - 提供小型嵌入式系统中抽象类的例子

c++ - 拖放 Win API 32

python - mod_wsgi错误:ImportError:dlopen(/usr/local/lib/python3.6/site-packages/cv2.so,2):找不到符号:_iconv

python - 如何在Python中不使用全局、 self 的情况下在每个函数调用中保留值

c++ - errnos在哪里定义的? i2c 的示例 linux c/c++ 程序

windows - SWI-Prolog 写入文件

c - 了解 GCC 内联汇编语法中的输入/输出操作数

python - SQLAlchemy 中与数据库无关的 MAX() 函数

python - 如何在opencv中合并轮廓?

memory - 多核架构中的CPU和内存访问