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?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…