I am struggling with a problem. I have Python program which send array to C++ exe . However I can't receive array from C++. My python code:
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:
// Comsol1.cpp : Defines the entry point for the console application. //
#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.