简体   繁体   English

Python和C++之间最基本的IPC

[英]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.我正在用 C++ 编写一个 DLL(Windows,MS VS 17),它需要在某个时候调用一个 Python 脚本——它应该读取一个 json 编码的字符串,处理它并返回 json 编码的结果。 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.不需要异步模式或“光速”,但我需要或多或少的快速响应 - 即最多在 1-5 秒内。 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.在我的情况下,最好避免这种做法,因为虽然我通常每次启动都需要运行 Python 部分一次,但启动次数可能相当大。
  3. Use a TCP/IP socket (for localhost ) / pipe .使用 TCP/IP 套接字(用于localhost )/管道 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.此外,在 Windows 中这可能会很痛苦。
  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.共享内存将是一个不错的选择,但我找不到在 C++ 和 Python 中使用相同段的方法。
  5. Embed Python part into C++ .将 Python 部分嵌入到 C++ 中 I have 2 concerns here: a) Python env should be installed on the target machine, shouldn't it?我在这里有两个问题:a) Python env 应该安装在目标机器上,不是吗? b) A python script has an import , which imports a package, installed from pip and, unfortunately, I cannot avoid it. b) python 脚本有一个import ,它导入一个包,从 pip 安装,不幸的是,我无法避免它。 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?在我的情况下,是否有一种简单的方法可以在 C++ 和 Python 之间进行互操作?

Since you're targeting Windows, option (2) is the best, but use a temporary file CreateFile(...FILE_ATTRIBUTE_TEMPORARY) .由于您的目标是 Windows,因此选项 (2) 是最好的,但请使用临时文件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.这实际上是共享内存(在操作系统级别,两者都由虚拟内存管理器管理),但您可以获得文件语义。

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

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