简体   繁体   中英

how to set shared memory between python and c++ in linux and osx

I was able to share memory on windows simply using winapi in cpp and mmap.mmap in python. just match "name".

And I was able to set the name of the shared memory using <boost/interprocess/shared_memory_object.hpp> on mac.

But python's mmap . mmap() didn't work. Even in the official documentation the parameters were different. It didn't have a parameter to set a name for.

So I gave up and decided to use <sys/ipc.h> .

It was able to communicate with python using the key, but write() to sysv_ipc in python gives the following error:

ValueError: Attempt to write past end of memory segment

  • python code
shm = sysv_ipc.SharedMemory(777)
if shm:
    offset = 0
    for idx in range(0, 21):
        shm.write(struct.pack(
            'f', hand_landmarks.landmark[idx].x), offset)
        offset += 4
        shm.write(struct.pack(
            'f', hand_landmarks.landmark[idx].y), offset)
        offset += 4
        shm.write(struct.pack(
            'f', hand_landmarks.landmark[idx].z), offset)
        offset += 4
  • c++ code
shmid = shmget(777, 512, IPC_CREAT | 0666)
shared_memory = shmat(shmid, NULL, 0)
fptr = reinterpret_cast<float *>(shared_memory);
for (int i = 0; i < 63; i += 3)
{
    std::cout << fptr[i] << " " << fptr[i + 1] << " " << fptr[i + 2] << "\n";
}

What should I do?

The issues is that shmget second parameters in in bits, not bytes.

So the correct way to write the code is:

shmid = shmget(777, 512 * 8, IPC_CREAT | 0666)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM