簡體   English   中英

使用stdout stdin將數組從C ++ exe傳遞給Python

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

我正在為一個問題而苦苦掙扎。 我有將數組發送到C ++ exe的Python程序。 但是我不能從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. 您正在打印到stderr而不是stdout,並且由於未通過stderr進行管道傳輸,因此您在運行python腳本時實際上會將消息打印到控制台。

  2. 您所打印的不僅僅是浮動到stdout,還不是原始二進制模式。 如果你希望讀彩車的名單out (在python),你必須只打印彩車(用C ++),並以二進制方式:

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

我在Ubuntu上嘗試了上述方法,並且工作正常。 您可以在這里找到我的源代碼。 我必須調整代碼才能在UNIX上工作,但是您可以理解。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM