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

楼主网上找了很久很久,都没有找到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....

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




  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值