Python subprocess Popen: Send binary data to C++ o

2019-03-02 11:23发布

After three days of intensive googleing and stackoverflowing I more or less got my program to work. I tried a lot of stuff and found a lot of answers somehow connected to my problem, but no working solution. Sry should I have missed the right page!! I'm looking forward to comments and recommendations.

Task:

  • Send binary data (floats) from python to C++ program, get few floats back
  • Data is going to be 20ms soundcard input, latency is a bit critical
  • Platform: Windows (only due to drivers for the soundcard...)
  • Popen with pipes, but without communicate, because I want to keep the C++ program opened

The whole thing worked just fine on ubuntu with test data. On Windows I ran into the binary stream problem: Windows checks the float stream for EOF character and finds it randomly. Then everything freezes, waiting for instream data which is just behind the "eof" wall. Or so I picture it.

In the end these two things were necessary:

#include <io.h>
#include <fcntl.h>

and

if (_setmode(_fileno(stdin), _O_BINARY) == -1) 
  {cout << "binary mode problem" << endl; return 1;};

in C++ as described here: https://msdn.microsoft.com/en-us/library/aa298581%28v=vs.60%29.aspx.

  • cin.ignore() freezes using binary mode! Guess since there's no eof anymore. Did not try/think about this too thoroughly though
  • cin.read(mem,sizeof(float)*length) does the job, since I know the length of the data stream
  • Compiled with MinGW

and in the Python code same thing! (forgot this first, cost me a day):

if sys.platform.find("win") > -1:
  import msvcrt,os      
  process = subprocess.Popen("cprogram.exe",stdin=subprocess.PIPE,stdout=subprocess.PIPE,bufsize=2**12)
  msvcrt.setmode(process.stdin.fileno(), os.O_BINARY)

and

process.stdin.write(data.tostring())

0条回答
登录 后发表回答