In a cross platform (Linux and windows) real-time application, I need the fastest way to share data between a C++ process and a python application that I both manage. I currently use sockets but it's too slow when using high-bandwith data (4K images at 30 fps).
I would ultimately want to use the multiprocessing shared memory but my first tries suggest it does not work. I create the shared memory in C++ using Boost.Interprocess and try to read it in python like this:
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
int main(int argc, char* argv[])
{
using namespace boost::interprocess;
//Remove shared memory on construction and destruction
struct shm_remove
{
shm_remove() { shared_memory_object::remove("myshm"); }
~shm_remove() { shared_memory_object::remove("myshm"); }
} remover;
//Create a shared memory object.
shared_memory_object shm(create_only, "myshm", read_write);
//Set size
shm.truncate(1000);
//Map the whole shared memory in this process
mapped_region region(shm, read_write);
//Write all the memory to 1
std::memset(region.get_address(), 1, region.get_size());
std::system("pause");
}
And my python code:
from multiprocessing import shared_memory
if __name__ == "__main__":
shm_a = shared_memory.SharedMemory(name="myshm", create=False)
buffer = shm_a.buf
print(buffer[0])
I get a system error FileNotFoundError: [WinError 2] : File not found
. So I guess it only works internally in Python multiprocessing, right ? Python seems not to find the shared memory created on C++ side.
Another possibility would be to use mmap but I'm afraid that's not as fast as "pure" shared memory (without using the filesystem). As stated by the Boost.interprocess documentation:
However, as the operating system has to synchronize the file contents with the memory contents, memory-mapped files are not as fast as shared memory
I don't know to what extent it is slower however. I just would prefer the fastest solution as this is the bottleneck of my application for now.