# How to use share memory 共享内存使用分为发送端和接收端,以下分别介绍 ## 发送端 **1. 添加共享内存消息格式文件** 共享内存中数据采用protobuf格式存储,Protobuf是一种平台无关、语言无关、可扩展且轻便高效的序列化数据结构的协议,可以用于**网络通信**和**数据存储**。 为使用共享内存,需添加一个相应的proto文件,文件位于`modularization/src/include/proto/hmi.proto`,可参考已有的文件编写 ```protobuf syntax = "proto2"; package iv.hmi; message hmimsg { required bool mbPause = 1; required bool mbBocheMode = 2; required bool mbbusmode = 3; }; ``` **2. 注册共享内存** 在工程配置文件***.pro中添加引用信息: ``` SOURCES += \ ../../include/msgtype/ui.pb.cc HEADERS += \ ../../include/msgtype/ui.pb.h LIBS += -lprotobuf INCLUDEPATH += $$PWD/../../include/msgtype LIBS += -L$$PWD/../../../bin/ -lmodulecomm ``` 设置共享内存名并注册: ```c++ std::string strmemvbox = "test" gpa = iv::modulecomm::RegisterSend(strmemvbox.data(),100000,3);iv::modulecomm::RegisterSend(strmemvbox.data(),100000,3); ``` 写入数据: ```c++ char * str = new char[gobj.ByteSize()]; //gobj是一个probuf数据,使用方法参考protobuf的使用 int nsize = gobj.ByteSize(); if(gobj.SerializeToArray(str,nsize)) { iv::modulecomm::ModuleSendMsg(gpa,str,nsize); } ``` **3. 直接发送proto消息** 包含头文件 #include "modulecommext.h" mpa = new iv::modulecommext::modulecommmsg(); mpa->RegisterSend("test"); ## 接收端 **1. 传统模式** 工程配置文件中添加配置信息: ```pro SOURCES += \ ../../include/msgtype/ui.pb.cc HEADERS += \ ../../include/msgtype/ui.pb.h LIBS += -lprotobuf INCLUDEPATH += $$PWD/../../include/msgtype LIBS += -L$$PWD/../../../bin/ -lmodulecomm ``` 源码中实现: ```c++ std::string strmemcan = “test”;//设置共享内存名字 iv::modulecomm::RegisterRecv(strmemcan.data(),listen); //数据接收函数,共享内存收到数据时,会调用: void listen(const char * strdata,const unsigned int nSize,const unsigned int index,const QDateTime * dt,const char * strmemname) { if(nSize<1)return; iv::can::canmsg xmsg; if(false == xmsg.ParseFromArray(strdata,nSize)) { std::cout<<"esr Listencan0 fail."<(); ModuleExtFun funext = std::bind(&testinteriorrecv::ListenMsg,this,std::placeholders::_1); mpa->RegisterRecvPlus("test"); void testinteriorrecv::ListenMsg(google::protobuf::Message &xmsg) { iv::testmodulecommext xdata; xdata.CopyFrom(xmsg); qDebug("Inter: %lld",xdata.time()); }