Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Communication between C++ and Python

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

like image 898
erling Avatar asked Aug 19 '14 12:08

erling


People also ask

How do you communicate with python and C?

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.

Is python connected to C?

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.


2 Answers

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.

like image 196
loopbackbee Avatar answered Sep 19 '22 12:09

loopbackbee


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.

like image 29
anil dhyani Avatar answered Sep 21 '22 12:09

anil dhyani