Python 共享内存 与 Qt c++ 程序进程之间通信
这里Python 使用 shared_memory
QT 使用 QSharedMemory
简单协议:
第一个是数据长度
后面是数据
python 代码:
from multiprocessing import shared_memory
import numpy as np
from PIL import Imageimport matplotlib.pyplot as pltif __name__ == "__main__":# python创建的共享内存的名称# 对应QSharedMemory 的 nativeKeyshared_memory_key = "my_share_mem" # [数据长度=15 数据=1-15]origin_data = np.array([15,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15])print(f"origin_data.dtype : {origin_data.dtype}")#------------- 数据写入共享内存# 创建共享内存对象shm_a = shared_memory.SharedMemory(create=True, name=shared_memory_key,size=origin_data.nbytes)#构造关联共享内存的数组mem_array = np.ndarray(origin_data.shape, dtype=origin_data.dtype, buffer=shm_a.buf)#copy 数据到共享内存mem_array[:]=origin_data[:]print(f"------------mem_array------------:\n{mem_array}\n")print(f"shm_a : {shm_a}")# 显示一张图片,阻止进程结束,等待Qt c++程序 访问共享内存img_path = "C:\\Users\\mingxingwang\\Pictures\\qt-logo.png"# 打开图片并转换为numpy数组img = Image.open(img_path)plt.imshow(img)plt.show()# 关闭共享内存shm_a.close()shm_a.unlink()
运行查看打印:
origin_data.dtype : int32
------------mem_array------------:
[15 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]shm_a : SharedMemory('my_share_mem', size=64)
QT 程序
#include <QSharedMemory>
#include <QBuffer>
#include <QDataStream>QSharedMemory *sm;sm = new QSharedMemory();// sm->setKey("my_share_mem");/// 与非Qt 程序通信 setNativeKeysm->setNativeKey("my_share_mem");if(!sm->attach()){qDebug()<<"attach error";return;}qDebug() << "attach success";QBuffer buffer;sm->lock();buffer.setData((char*)sm->data(),sm->size());sm->unlock();sm->detach();if(!buffer.open(QBuffer::ReadOnly)){qDebug()<<"open buffer error";return;}QDataStream in(&buffer);in.setByteOrder(QDataStream::LittleEndian);int len=0;int tmp=0;in >> len;qDebug()<<"len"<<len;for(int i=0;i<len;i++){in >>tmp;qDebug()<<QString::asprintf("buf[%d] = %04x",i,tmp);}
运行查看打印:
attach success
len 15
"buf[0] = 0001"
"buf[1] = 0002"
"buf[2] = 0003"
"buf[3] = 0004"
"buf[4] = 0005"
"buf[5] = 0006"
"buf[6] = 0007"
"buf[7] = 0008"
"buf[8] = 0009"
"buf[9] = 000a"
"buf[10] = 000b"
"buf[11] = 000c"
"buf[12] = 000d"
"buf[13] = 000e"
"buf[14] = 000f"