Communication between C++ and Python

生来就可爱ヽ(ⅴ<●) 提交于 2020-06-25 03:22:35

问题


I am looking for an efficient and smart way to send data between a C++-program and a Python-script. I have a C++ program which calculates some coordinates in-real-time 30Hz. And I wanna access these coordinates with a Python-script. My first idea was to simply create a .txt-file and write the coordinates to it, and then have Python open the file and read. But I figured that it must be a smarter and more efficient way using the RAM and not the harddrive.

Does anyone have any good solutions for this? The C++ program should write 3coordinates (x,y,z) to some sort of buffer or file, and the Python program can open it and read them. Ideally the C++-program overwrites the coordinates every time and there's no problem with reading and writing to the file/buffer at the same time.

Thank you for your help


回答1:


You have two basic options:

  • Run the C++ code and the python code as two separate programs, in two separate processes, and use a IPC mechanism
  • Link the C++ code against your code, as grc suggested.

The first option is probably better if you already have a complete complex C++ program written. Also, it's generally easier to debug and maintain.

As for a specific IPC mechanism, sockets are commonly used because they have somewhat standardized cross-platform APIs at the OS level, and still work if you need the two programs running on different machines. Sockets should be more than enough for transferring three coordinates 30 times each second, if you're dealing with a modern desktop machine.

If you really need more performance, you could look into (named or named) pipes, but you'll probably need some extra work on the C++ side to make it cross-platform.




回答2:


I think we can use Named Pipes for communication between a python and C++ program if the processes are on the same machine.

However for different machines sockets are the best option.



来源:https://stackoverflow.com/questions/25383624/communication-between-c-and-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!