如何使用sendto()发送结构 [英] How to Send a structure using sendto()

查看:249
本文介绍了如何使用sendto()发送结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已创建结构:

struct buffer
{
    string ProjectName ;
    string ProjectID ;
}

buffer buf;
buf.ProjectID = "212";
buf.ProjectName = "MyProj";



现在要使用sendto方法发送这个结构,我将typecasting结构并发送回如下:

Now to send this structure using sendto method , I am typecasting the strucure and sending it back as below:

char *sendbuf = (char*)&buf;
sentbytes = sendto(sock,sendbuf,strlen(sendbuf),0,(sockaddr*)&their_addr,sizeof(their_addr));

但是当我投射我的Struct ti char * 实际数据丢失它的值,而调试我看到sendbuf包含一些其他值。

But while I am casting my Struct ti char* the actual data is loosing it's values and while debugging I see sendbuf is containing some other values.

有人可以让我知道如何发送上述结构sendto。

Can some one let me know how can I send the above structure using sendto.

推荐答案

您需要使用POD创建结构,字符串不是可以使用的方式。您需要声明类似

You need to create the structure using POD, the string is not something you can use in that way. Instead you need to declare it something like

struct buffer
{
  char ProjectName[MAX_LENGTH_PROJECT_NAME+1];
  char ProjectID[MAX_LENGTH_PROJECT_ID+1];
};

编辑:澄清,字符串包含一个指向堆分配的内存块的指针,在尝试发送该结构时发送字符。

clarification, the string contains a pointer to a heap allocated memory block, so you are not actually sending the characters when you try to send that structure.

这篇关于如何使用sendto()发送结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆