繁体   English   中英

如何在 linux 和 OS 中的 python 和 c++ 之间设置共享 memory

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

我能够在 windows 上共享 memory ,只需使用 cpp 中的 winapi 和 Z2D33EEEB4347BDD7526 中的 mmap.mmap 只匹配“名称”。

我能够在 mac 上使用<boost/interprocess/shared_memory_object.hpp>设置共享 memory 的名称。

但是 python 的mmap mmap()不起作用。 即使在官方文档中,参数也是不同的。 它没有设置名称的参数。

所以我放弃了,决定使用<sys/ipc.h>

它能够使用密钥与 python 进行通信,但是sysv_ipc中的 sysv_ipc 的write()会给出以下错误:

ValueError:尝试写入 memory 段的末尾

  • python代码
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++代码
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";
}

我应该怎么办?

问题是shmget第二个参数以位为单位,而不是字节。

所以编写代码的正确方法是:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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