问题描述
问题
如何使用c ++流(如 std :: ifstream $ c $来自Cython的c>或
ostream
)?在c ++中,您可以执行以下操作:
How does one use c++ streams (like std::ifstream
or ostream
) from Cython? In c++, you could do the following:
std::ofstream output { filename, std::ios::binary };
output.write(...);
你如何在Cython中实现同样的目标?
How would you achieve the same in Cython?
当前状态
我已经在Cython中包装了fstream中的结构,以便我可以在函数声明中使用它们的名称,但是很棘手部分是使用(在Cython中包装,也许)写入方法并创建流。我没有在互联网上找到任何代码示例。
I have wrapped the structures from fstream in Cython so that I can use their names in function declarations, but the tricky part is to use (wrap in Cython, perhaps) the write method and to create the streams. I haven't found any code examples on the internet.
P.S。
我知道一个可能的答案就是使用Python的IO,但我需要传递/返回与我正在连接的C ++代码的流。
P.S.I know one possible answer would be to just use Python's IO but I need to pass/return the streams to and from C++ code that I'm interfacing with.
这是包装流声明的代码:
This is the code that wraps the stream declarations:
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
是一个命名空间而不是一个类。
There isn't much particularly special about the c++ iostreams compared to wrapping any other C++ class. The only tricky bit was getting access to std::ios_base::binary
, which I did by telling Cython that std::ios_base
was a namespace and not a class.
# 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
要添加的另一件事是我没有使用完整的模板化类heirarchy - 如果你还想要 wchar可能会有用
变体,但只告诉Cython你实际使用的类更容易。
The other thing to add is that I haven't bothered with the full templated class heirarchy - that might be useful if you also want the wchar
variants, but it's much easier to only tell Cython about the classes you're actually using.
这篇关于Cython:使用C ++流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!