Cython: working with C++ streams
Cython: working with C++ streams
问题
如何使用Cython的c++流(如std::ifstream
或ostream
)?在c++中,您可以执行以下操作:
std::ofstream output { filename, std::ios::binary };
output.write(...);
在Cython,你是如何做到这一点的?
当前状态
我已经将fstream中的结构封装在Cython中,这样我就可以在函数声明中使用它们的名称,但棘手的部分是使用(可能是在Cytho中封装)write方法并创建流。我在网上没有找到任何代码示例。
第页。S我知道一个可能的答案是只使用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你实际使用的类要容易得多。
相关文章:
- 面临分段故障 使用 ffmpeg 读取视频时,因为"pFormatCtx-> streams [i]-> codecpar"的地址0x00
- 如何创建一个 while 循环,继续循环,直到在C++中输入'using streams'键?
- C++应用程序缺少 winrt::Windows::Storage::Streams::D ataWriter
- Introduction To C++ IO Streams
- 为什么cpplint不鼓励Streams
- Streams中的内联忽略
- 在C++std::streams中,失败后,如何获得失败原因?必需:线程安全,适用于Windows和Linux(或至少M
- 从 Windows::Storage::Streams::IBuffer 中获取字节数组
- GCC, std::ctype specialisation & streams
- cstdio streams vs iostream streams?
- C++ io streams versus mmap
- C++11 File Streams
- c++ JNI在做任何IO/Streams时崩溃/挂起
- boost::streams::output过滤器的意外行为
- Including windows.storage.streams.h
- Override c++ streams
- Cython: working with C++ streams