开发者

How to Send a structure using sendto()

开发者 https://www.devze.com 2023-01-14 00:29 出处:网络
I have created structure : struct buffer { string ProjectName ; string ProjectID ; } buffer buf; buf.ProjectID = \"212\";

I have created structure :

struct buffer
{
    string ProjectName ;
    string ProjectID ;
}

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

Now to send this structure using sendto method , I am typecasting the strucure and sending it bac开发者_StackOverflow社区k as below:

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

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.

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


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];
};

EDIT: 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.


std::string holds its data in dynamically allocated memory. You could send separately each string and length of a string which you can get by using std::string::c_str and std::string::size.


Prefer using marshall/unmarshall when sending data over network. A C++-style is to use "<< / >>" for streaming to a sendable buffer. This way, you have more control over what you are sending and how it is sent (binary,text,xml,...). Boost also has a serialization module.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号