通过stdout和stdin将数组从C++可执行文件传递给Python
我遇到了一个问题。我有一个Python程序,它可以把一个数组发送给C++的可执行文件(exe)。但是我无法从C++那边接收到数组。我的Python代码是:
import struct
import subprocess
from cStringIO import StringIO
stdin_buf = StringIO()
array = [1.0 for _ in range(10)]
for item in array:
stdin_buf.write(struct.pack('<f', item))
proc = subprocess.Popen(['Comsol1.exe'], stdin=subprocess.PIPE, stdout = subprocess.PIPE)
out, err = proc.communicate(stdin_buf.getvalue())
# assuming the result comes back the same way it went in...
item_len = struct.calcsize('<f')
stdout_buf = StringIO(out)
stdout_buf.seek(0)
for i in range(len(out)/item_len):
val = struct.unpack('<f', stdout_buf.read(4))
print (val)
C++代码:
// Comsol1.cpp : 定义了这个控制台应用程序的入口点。
#include "stdafx.h"
#include <streambuf>
#include "stdafx.h"
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
#include <iostream>
int main(void)
{
int result;
// Set "stdin" to have binary mode:
result = _setmode(_fileno(stdin), _O_BINARY);
if (result == -1)
perror("Cannot set mode");
else
fprintf(stderr, "'stdin' successfully changed to binary mode\n");
// Set "stdout" to have binary mode:
result = _setmode(_fileno(stdout), _O_BINARY);
if (result == -1)
perror("Cannot set mode");
else
fprintf(stderr, "'stdout' successfully changed to binary mode\n");
int i = 0;
while (!std::cin.eof())
{
float value;
std::cin.read(reinterpret_cast<char*>(&value), sizeof(value));
if (std::cin.gcount() > 0)
{
std::cerr << "Car " << i << ": " << value << std::endl;
i++;
}
}
}
谢谢。
1 个回答
1
你这里有两个问题:
你把信息打印到了错误输出(stderr)而不是标准输出(stdout)。因为错误输出没有被管道连接,所以当你运行你的 Python 脚本时,信息会直接显示在控制台上。
你打印的内容不仅仅是浮点数,而且不是以原始二进制模式输出。如果你希望从
out
(在 Python 中)读取浮点数列表,你需要在 C++ 中只打印浮点数,并且要使用二进制模式:std::cout.write(reinterpret_cast<const char*>(&value), sizeof(value));
我在 Ubuntu 上尝试了上述方法,效果很好。你可以在 这里找到我的源代码。我对代码做了一些调整以便在 Unix 上运行,但你可以理解大概意思。