简体   繁体   English

使用stdout stdin将数组从C ++ exe传递给Python

[英]Pass array from C++ exe to Python using stdout stdin

I am struggling with a problem. 我正在为一个问题而苦苦挣扎。 I have Python program which send array to C++ exe . 我有将数组发送到C ++ exe的Python程序。 However I can't receive array from C++. 但是我不能从C ++接收数组。 My python code: 我的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++ code: C ++代码:

// Comsol1.cpp : Defines the entry point for the console application. // 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++;
    }
}
      }

Thank you. 谢谢。

So you have two problems here: 因此,这里有两个问题:

  1. You are printing to stderr instead of stdout, and because stderr is not piped you'll actually get the messages printed to the console when you run your python script. 您正在打印到stderr而不是stdout,并且由于未通过stderr进行管道传输,因此您在运行python脚本时实际上会将消息打印到控制台。

  2. You are printing more than just floats to stdout and not in raw binary mode. 您所打印的不仅仅是浮动到stdout,还不是原始二进制模式。 If you expect to read a list of floats from out (in python) you have to print only the floats (in c++) and in binary mode: 如果你希望读彩车的名单out (在python),你必须只打印彩车(用C ++),并以二进制方式:

    std::cout.write(reinterpret_cast<const char*>(&value), sizeof(value));

I tried the above approach on Ubuntu and it's working properly. 我在Ubuntu上尝试了上述方法,并且工作正常。 You can find my source code here . 您可以在这里找到我的源代码。 I had to tweak the code to work on unix, but you can get the idea. 我必须调整代码才能在UNIX上工作,但是您可以理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM