【问题标题】:convert byte array to structure in c将字节数组转换为c中的结构
【发布时间】:2014-03-24 07:57:40
【问题描述】:

我正在用 C 语言开发一个客户端-服务器应用程序。

我想从客户端将结构作为字符数组发送,然后将字符数组转换回服务器端的结构。

我有以下结构

typedef struct mail{  
    char cc[30];   
    char bcc[30];  
    char body[30];  
}

typedef struct msg_s{   
    int msgId;  
    mail mail_l;    
}

我想向客户端发送 msg1。

unsigned char data[100];   
struct msg_s msg1 ;  
msg1.msgId=20;  
// suppose the data in mail structure is already filled.    
data = (unsigned char*)malloc(sizeof(msg1));  
memcpy(data, &msg1, sizeof(msg1));  
write(socketFd , data , sizeof(data)); 

当我在服务器端获取这些数据时,如何将其转换回结构?

我想用 C 和 java 语言做同样的事情。

如果可能的话,请给我推荐一些关于这个的好文章,如果我错过了这个概念的名称。

【问题讨论】:

  • struct msg_s = msg1 ; 应该是struct msg_s msg1;
  • data 是不可修改的右值,或类似的东西。 unsigned char data[100]; 应该是 unsigned char * data; 或者......我不知道,你不能像现在这样为其分配 malloc 的地址。
  • Google 一些关于不同 int 大小(甚至可能是不同的浮点约定)、结构成员顺序、结构打包/填充,当然还有字节序的信息。 ->序列化并没有你想的那么简单。

标签: c arrays serialization struct deserialization


【解决方案1】:

我看到很多错误,

首先, Character array declaration inside struct mail doesn't following the C convention

应该是这样的,

typedef struct mail{  
    char cc[30];   
    char bcc[30];  
    char body[30];  
}

第二

struct msg_s = msg1 ; 更改为struct msg_s msg1 ; // its a declaration of a struct msg1

第三个

unsigned char data[100]; 在静态内存中分配 100 字节内存。

并且您正在通过data = (unsigned char*)malloc(sizeof(msg1)); 再次分配大小为 struct msg1 的动态内存 [heap]。

unsigned char data[100]; 更改为unsigned char *data;

在客户端,

struct msg_s *inMsg ;  
inMsg = malloc(sizeof(struct msg_s));  // malloc in c doesn't require typecasting
memcpy(inMsg ,data, sizeof(struct msg_s));  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-17
    • 1970-01-01
    • 2015-11-18
    • 1970-01-01
    • 1970-01-01
    • 2011-10-04
    • 1970-01-01
    相关资源
    最近更新 更多