简体   繁体   English

如何使用 c++ boost::interprocess 库通过命名共享 memory 与 Python 通信?

[英]How to use c++ boost::interprocess library to communicate with Python through named shared memory?

Purpose: Let c++ process communicate with python process on this computer, and intend to use shared memory to communicate.目的:让c++进程与本机上的python进程进行通信,打算使用共享的memory进行通信。 C++ uses the boost::interprocess library to create a named shared memory through shared_memory_object, and writes data into it, while python reads the corresponding data. C++使用boost::interprocess库通过shared_memory_object创建一个命名共享memory,并向其中写入数据,而python则读取相应的数据。

Question: how does python access data based on the name of the corresponding shared memory in c++?问题:python如何根据c++中对应的共享memory的名称访问数据?

Here's the clip I wrote:这是我写的剪辑:

          struct test_datas {
            char name[128];
            char sender[128];
            union u_data {
                char s1_[1024];
                long l1_;
                double d_;
            } u_member;
        };
        
        void write_shared_memory() {
            using namespace boost::interprocess;
            shared_memory_object shdmem(open_or_create , "monika", read_write);
            shdmem.truncate(sizeof(test_datas));
            mapped_region region(shdmem , read_write);
        
            auto *data_ptr = static_cast<test_datas *>(region.get_address());
            sprintf(data_ptr->name , "%s" , "named");
            sprintf(data_ptr->sender , "%s" , "myself");
            data_ptr->u_member.d_ = 66.890;
    }

Here is the corresponding Python code:这是对应的 Python 代码:

    from multiprocessing import shared_memory
    
    if __name__ == "__main__":
        shm_a = shared_memory.SharedMemory(name="monika", create=False)
        buffer = shm_a.buf
        print(buffer[0])

    error: FileNotFoundError: [WinError 2] The system cannot find the file specified: 'monika'

Assuming POSIX (eg Linux) here, both create SHM "files", so on say Ubuntu /dev/shm/monika.假设这里是 POSIX(例如 Linux),两者都创建 SHM“文件”,所以说 Ubuntu /dev/shm/monika。

However, it seems that Python by default attempts to clean it up.但是,默认情况下 Python 似乎会尝试清理它。 See docs :请参阅文档

When one process no longer needs access to a shared memory block that might still be needed by other processes, the close() method should be called.当一个进程不再需要访问其他进程可能仍需要的共享 memory 块时,应调用 close() 方法。

However, this suggests that the Python shared memory facility is much less general purpose than usual, see eg Shared memory deleted at exit但是,这表明 Python 共享 memory 设施的通用性远低于通常情况,例如,共享 memory 在退出时删除

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

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