我有一个用 C++ 编写的库,它使用标准流来读取和写入对象。我还有一个用 Swig 生成的 Python 接口,我用它来访问该库。在 Linux 上一切正常,但在 Windows(在 MinGW 上)上似乎不可能通过 Python 接口以二进制模式使用 C++ 标准流。如果在文本模式下使用流,则额外的 CR 字符会破坏库。标准流完全封装在 C++ 库中,即我没有通过 Python 接口传递它们。
我尝试过一种适用于使用该库的 C++ 程序的解决方案,即添加以下行
#include <fcntl.h>
int _CRT_fmode = _O_BINARY;
块内
%{
#define SWIG_FILE_WITH_INIT
...
%}
在 Swig libfoo.i 文件中,但没有任何效果。还增加了一个功能
void set_binary_mode() {
assert(stdin == freopen(0, "rb", stdin));
assert(stdout == freopen(0, "wb", stdout));
}
在Python程序的开头调用它似乎没有任何作用。还在Python程序的开头执行这些行
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)
没有影响。前面的任何组合也不起作用。
我正在 Windows XP 版本 2002 上的 MinGW32(20120426 下载的版本)上编译 C++ 库和 Swig/Python 绑定。我使用的工具版本是 Python (2.7.3)、Swig (2.0.8 )和海湾合作委员会(4.6.2)。