I'm trying to connect a C++ program to python using shared memory but I don't know how to pass the name of the memory segment to python.
Here is my C++ code:
key_t key = ftok("address", 1);
int shm_o;
char* msg = "hello there";
int len = strlen(msg) + 1;
void* addr;
shm_o = shmget(key, 20, IPC_CREAT | 0600);
if(shm_o == -1)
{
std::cout << "Failed: shmget.\n";
return 1;
}
addr = shmat(shm_o, NULL, 0);
if(addr == (void*) -1)
{
std::cout << "Failed: shmat.\n";
return 1;
}
std::cout << "Shared memory segment created successfully with id: " << shm_o;
memcpy(addr, msg, len);
getchar();
return 0;
I'm trying to get python to read from the shared memory segment like so:
shm_a = shared_memory.SharedMemory(name="address", create=False, size=20)
print(bytes(shm_a.buf[:11]))
but it throws an exception saying there is no file or directory called 'address'.
Am I going about this correctly or is there another way to attach python to the shared memory segment?
Any help would be much appreciated.
ipcs -m.multiprocessingmodule uses Posix shared memory, not SysV shared memory (despite the documentation's claim that it's "System V style" shared memory). On Windows, it uses a different system. Interfacing with C++ (or C) would require the same dual implementation, I think. But shmget is not part of either of them.shm_openandshm_unlinkfrom<sys.mman.h>