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
You could start the C program from the python program using the subprocess module. In that case you could write from the python program to the standard input of the C program. This is probably the easiest way. N.B. if you want to send data multiple times, then you should not use Popen.
The rawest, simplest way is to use the Python C API and write a wrapper for your C library which can be called from Python. This ties your module to CPython. The second way is to use ctypes which is an FFI for Python that allows you to load and call functions in C libraries directly.
You have two basic options:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With