Using C++ standard streams in binary mode through

2019-07-15 03:06发布

问题:

I have a library written with C++ that uses standard streams to read and write objects. I also have a Python interface generated with Swig that I'm using to access the library. Everything works fine on Linux, but on Windows (on MinGW) it seems impossible to use C++ standard streams in binary mode through the Python interface. If the streams are used in text mode, the extra CR characters break the library. The standard streams are fully wrapped inside the C++ library, i.e. I'm not passing them through the Python interface.

I have tried a solution that works in C++ programs that use the library, i.e. adding the lines

#include <fcntl.h>
int _CRT_fmode = _O_BINARY;

inside the block

%{
#define SWIG_FILE_WITH_INIT
...
%}

in the Swig libfoo.i file, but it has no effect. Also adding a function

void set_binary_mode() {
  assert(stdin == freopen(0, "rb", stdin));
  assert(stdout == freopen(0, "wb", stdout)); 
}

and calling it in the beginning of the Python program seems to do nothing. Also executing in the beginning of the Python program the lines

sys.stdin = os.fdopen(sys.stdin.fileno(), 'rb', 0)
sys.stdout = os.fdopen(sys.stdout.fileno(), 'wb', 0)

and/or

if sys.platform == "win32":
  import msvcrt
  msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
  msvcrt.setmode(sys.stderr.fileno(), os.O_BINARY)

have no effect. Any combination of the previous doesn't work either.

I'm compiling the C++ library and the Swig/Python bindings on MinGW32 (version downloaded on 20120426) on Windows XP version 2002. The versions of the tools that I'm using are Python (2.7.3), Swig (2.0.8) and gcc (4.6.2).