Is there a way to use std::[io]fstream
\'s in python via swig?
I have a c-class with functions like:
void readFrom(std::istream& istr
I made a few tweaks to the solution provided by @Flexo
The main change was to use a boost::iostream::stream owned by a unique pointer
Some other differences:
%fragment("iostream_header", "header") %{
#include
#include
#include
#include
using boost_ofd_stream = boost::iostreams::stream;
using boost_ifd_stream = boost::iostreams::stream;
%}
%typemap(in, fragment="iostream_header") std::ostream& (std::unique_ptr stream) {
PyObject *flush_result = PyObject_CallMethod($input, const_cast("flush"), nullptr);
if (flush_result) Py_DECREF(flush_result);
%#if PY_VERSION_HEX < 0x03000000
int fd = fileno(PyFile_AsFile($input));
%#else
int fd = PyObject_AsFileDescriptor($input);
%#endif
if (fd < 0) { SWIG_Error(SWIG_TypeError, "File object expected."); SWIG_fail; }
stream = std::make_unique(fd, boost::iostreams::never_close_handle);
$1 = stream.get();
}
%typemap(in, fragment="iostream_header") std::istream& (std::unique_ptr stream) {
%#if PY_VERSION_HEX < 0x03000000
int fd = fileno(PyFile_AsFile($input));
%#else
int fd = PyObject_AsFileDescriptor($input);
%#endif
if (fd < 0) { SWIG_Error(SWIG_TypeError, "File object expected."); SWIG_fail; }
stream = std::make_unique(fd, boost::iostreams::never_close_handle);
$1 = stream.get();
}