Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
599 views
in Technique[技术] by (71.8m points)

How to implement process communication between C++ and python via shared memory on linux systems?

I have implemented it on windows using boost.interprocess. The c++ codes are as follows:

#ifndef TRANSFER_DATA_H
#define TRANSFER_DATA_H
#include <iostream>
#include <cstring>

struct TransferData
{
   char letters[100];
};

void fill(TransferData* data)
{
   strcpy(data->letters,"Hello world");
}
   
#endif // TRANSFER_DATA_H

the main.cpp is like this:

#include "TransferData.h"
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/windows_shared_memory.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <bits/stdc++.h>

using namespace boost::interprocess;

int main(int argc, char* argv[])
{
   if (argc > 1)
   {
      // Get Data
      windows_shared_memory shmem(open_only, "TransferDataSHMEM", read_write);
      mapped_region region(shmem, read_write);

      TransferData* data = reinterpret_cast<TransferData*>(region.get_address());

      std::cout << "C++ Program - Getting Data" << std::endl;
      std::cout << data->letters << std::endl;
   }
   else
   {
      // Create Data
      windows_shared_memory shmem(create_only, "TransferDataSHMEM",
         read_write, sizeof(TransferData));

      mapped_region region(shmem, read_write);
      std::memset(region.get_address(), 0, sizeof(TransferData));

      TransferData* data = reinterpret_cast<TransferData*>(region.get_address());

      std::cout << "C++ Program - Filling Data" << std::endl;
      fill(data);
      std::system("pause");
   }
   return 0;
}

python program to get data is as follows:

import ctypes
class TransferData(ctypes.Structure):
    _fields_=[
        ('letters',ctypes.c_char*100)
    ]
import sys
import mmap
if __name__ == '__main__':
    shmem = mmap.mmap(-1, ctypes.sizeof(TransferData), 
                  tagname = "TransferDataSHMEM")
    data = TransferData.from_buffer(shmem)
    print('Python Program - Getting Data')
    print(data.letters)
    input("Press Enter to continue...")

but obviously "windows_shared_memory" object cannot support on linux systems. If I changed windows_shared_memory to shared_memory_object, after compiling, I get a memory error while running the program. The Python codes cannot work well on linux system either. I don't wanna make a linux device for communication between C++ and python. So how can I do? Does boost have suitable module or class object for that?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...