将字节数组转换为c中的结构体

标签 c arrays serialization struct deserialization

我正在用 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 语言做同样的事情。

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

最佳答案

我看到很多错误,

首先, 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 的动态内存 [堆] .

更改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));  

关于将字节数组转换为c中的结构体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22603824/

相关文章:

c - 局部函数、静态函数和全局函数之间的区别?

c - 从 `forkpty` 子进程读取 : `ls/` output yields `EIO`

javascript - 如果数组有特定值

2015 年的 Java 进程间通信(没有样板)?

c# - 如何将弱类型 JSON 转换为 C# 可读对象

无法将 char 分配给 char 指针

c - 使用 c 的对象树?

iphone - 如何在 Objective-C 中使用 C 语言数组

php - 打印数组的偶数和(排序的)奇数

C++ json反序列化器