简体   繁体   中英

The most basic IPC between Python and C++

I'm writing a DLL (Windows, MS VS 17) in C++ which requires to call a Python script at some point - it should read a json-encoded string, process it and give back the json-encoded result. There is no need for asynchronous mode or "speed of light", but I need more or less fast response - ie within 1-5 seconds max. Here are the approaches I considered and the comments:

  1. Pass the string as a command line argument . This is, obviously, not the best choice - let alone string length limit.
  2. Use a temporary file . It will be the best to avoid such practice in my case, because although I need to run the Python-part generally once per launch, the number of launches may be quite big.
  3. Use a TCP/IP socket (for localhost ) / pipe . Both seem to be an overkill for such a task - I do not have a continuous flow of data which changes constantly. Besides, in Windows it might be a pain.
  4. Use shared memory . Shared memory would be a nice option but I couldn't find a way to use the same segment both in C++ and Python.
  5. Embed Python part into C++ . I have 2 concerns here: a) Python env should be installed on the target machine, shouldn't it? b) A python script has an import , which imports a package, installed from pip and, unfortunately, I cannot avoid it. Is there a proper way to work with imports when embedding?

Is there a simple way to interoperate between C++ and Python in my case?

Since you're targeting Windows, option (2) is the best, but use a temporary file CreateFile(...FILE_ATTRIBUTE_TEMPORARY) . That's effectively shared memory (at the OS level, both are managed by the Virtual Memory Manager) but you get file semantics.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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