Socket Send 带多指针的结构体,变长字符串,stringchar[] 等等。。

xiaoxiao2021-02-27  133

楼主网上找了很久很久,都没有找到Socket Send 带多指针的结构体的方法,有说发数组的,有说只能发一个指针的,但是我接下来要说的是,发送带多指针的结构体;

1.Socket的初始化我就不写了,网上很多,而且很固定;

2.定义一个多指针的结构体;

struct SendMsgForMat { char* Msg; //错误信息 char* BigBarcode; //大条码 int MsgSize; //错误信息长度 int BigBarcodeSize; //大条码长度 };

std::string pStrMsg = "Unknown Error";

char cAoiBarcode[30] = "123456";

SendMsgForMat SendErrorMsg; //实例化这个结构体

SendErrorMsg.MsgSize = pStrMsg.length(); //错误信息的长度 SendErrorMsg.BigBarcodeSize = sizeof(cAoiBarcode); //大条码的长度

ss = sizeof(SendMsgForMat)+SendErrorMsg.MsgSize + SendErrorMsg.BigBarcodeSize + 1     //发送长度

char *sendPmsg = new char[sizeof(SendMsgForMat)+SendErrorMsg.MsgSize + SendErrorMsg.BigBarcodeSize + 1];//new一个需要发送的字符串

ZeroMemory((void*)sendPmsg, sizeof(SendMsgForMat)+SendErrorMsg.MsgSize + SendErrorMsg.BigBarcodeSize + 1);

//初始化为0;不然可能出现多信息的情况

memcpy((void*)(sendPmsg), (void*)&SendErrorMsg, sizeof(SendMsgForMat));

//拼接结构体长度在sendPmsg 后方

memcpy((void*)(sendPmsg + sizeof(SendMsgForMat)), (void*)pStrMsg.c_str(), SendErrorMsg.MsgSize);

//拼接结构体Msg成员在sendPmsg 后方

memcpy((void*)(sendPmsg + sizeof(SendMsgForMat)+SendErrorMsg.MsgSize), (void*)cAoiBarcode, SendErrorMsg.BigBarcodeSize);

//拼接结构体BigBarcode成员在sendPmsg 后方

int ret = send(m_socket1, (const char *)sendPmsg, ss, 0);//发送

delete[] sendPmsg; //记得释放

捣鼓了两天,终于实现了,完美!!!

这里面有很多坑:

1.为什么不SendErrorMsg.Msg = pStrMsg.c_str();这样子赋值???

2.为什么一定要用memcpy???

3....

接收部分就交给你们自己发挥了。

转载请注明原文地址: https://www.6miu.com/read-15550.html

最新回复(0)