简体   繁体   English

使用共享 memory 将 C++ 程序连接到 Python 脚本

[英]Connecting a C++ program to a Python script with shared memory

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. 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:这是我的 C++ 代码:

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:我试图让 python 从共享的 memory 段中读取,如下所示:

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?我是否正确地解决了这个问题,或者是否有另一种方法将 python 连接到共享的 memory 段?

Any help would be much appreciated.任何帮助将非常感激。

Taking the liberty to post a working example here for POSIX shared memory segments, which will work across C/C++ and Python on Linux/UNIX-like systems.冒昧地在这里为 POSIX 共享 memory 段发布一个工作示例,它将在 Linux/UNIX 类系统上跨 C/C++ 和 Python 工作。 This will not work on Windows.不适用于 Windows。

C++ code to create and write data into a shared memory segment (name provided on command line): C++ 代码用于创建数据并将其写入共享 memory 段(命令行中提供的名称):

#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

#include <iostream>
#include <string>

int main(int argc, char * argv[])
{
    if (argc != 2) {
         std::cerr << "Argument <shmem_name> required" << std::endl;
         return 1;
    }
    const char * shmem_name = argv[1];
    size_t shm_size = 4096;
    int shmem_fd = shm_open(shmem_name, O_CREAT|O_RDWR, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP);
    if (shmem_fd == -1) {
         perror("shm_open");
         return 1;
    }
    std::cout << "Shared Memory segment created with fd " << shmem_fd << std::endl;
    if (ftruncate(shmem_fd, shm_size) == -1) {
        perror("ftruncate");
        return 1;
    }
    std::cout << "Shared Memory segment resized to " << shm_size << std::endl;
    void * addr = mmap(0, shm_size, PROT_WRITE, MAP_SHARED, shmem_fd, 0);
    if (addr == MAP_FAILED) {
        perror("mmap");
        return 1;
    }
    std::cout << "Please enter some text to write to shared memory segment\n";
    std::string text;
    std::getline(std::cin, text);
    while (! text.empty()) {
        strncpy((char *)addr, text.data(), shm_size);
        std::cout << "Written '" << text << "' to shared memory segment\n";
        std::getline(std::cin, text);
    }
    std::cout << "Unlinking shared memory segment." << std::endl;
    shm_unlink(shmem_name) ;
}

Python code to read any string from the beginning of the shared memory segment: Python 代码从共享 memory 段的开头读取任何字符串:

import sys
from multiprocessing import shared_memory, resource_tracker

if len(sys.argv) != 2:
    print("Argument <shmem_name> required")
    sys.exit(1)

shm_seg = shared_memory.SharedMemory(name=sys.argv[1])
print(bytes(shm_seg.buf).strip(b'\x00').decode('ascii'))
shm_seg.close()
# Manually remove segment from resource_tracker, otherwise shmem segment
# will be unlinked upon program exit
resource_tracker.unregister(shm_seg._name, "shared_memory")

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

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