这是我一直在研究很长时间的东西,但无法解决为什么它不能正常工作,希望你能帮我解决一些问题!我会尽量做到描述性。
这个想法是序列化一个结构(NIPC数据包结构),通过TCP发送到另一个进程,然后反序列化并重新构建这个结构。但不知何故,我无法让它正常工作,只是部分地。这里是结构。
typedef struct {
char pct_type;
short int payload_lenght;
}__attribute__((__packed__)) t_header;
typedef struct {
char* path;
long unsigned int size;
long int offset;
}__attribute__ ((__packed__)) t_payload_read;
typedef struct {
t_header header;
t_payload_read payload;
}__attribute__ ((__packed__)) t_pct_read;
然后,我首先序列化了有效载荷(偏移量、大小和路径),以计算有效载荷的长度,然后是整个数据包,包括要发送的标头。然后反序列化,但没有办法让它工作,另一方面,我得到标题 OK 和路径字段“OK”,但我得到关于偏移量和大小的奇怪数字,例如,使用这个硬编码值结构体:
type: 4
offset: 5
size: 15
path: ~/Desarrollo/Workspace
我得到:
pct->header.pct_type: 4
pct->header.payload_length: 28
pct->payload.path: ~/Desarrollo/Workspac
pct->payload.size: 143994937
pct->payload.offset: 143994941
在这里我附加了我设计的序列化和反序列化函数,我尽量做到描述性和仔细。
char* serialize_read(t_pct_read* packet) {
char* buffer = malloc(
sizeof(t_header) + sizeof(packet->payload.offset)
+ sizeof(packet->payload.size)
+ strlen(packet->payload.path + 1));
char* payload = malloc(
sizeof(packet->payload.offset) + sizeof(packet->payload.size)
+ strlen(packet->payload.path) + 1);
int offset;
// First I serialize the Payload, in order to calculate It's lenght
memcpy(payload, packet->payload.path, strlen(packet->payload.path) + 1);
offset = strlen(packet->payload.path)+1;
memcpy(payload + offset, &packet->payload.size, sizeof(long unsigned int));
offset += (sizeof(long unsigned int));
memcpy(payload + offset, &packet->payload.offset, sizeof(long int));
packet->header.payload_lenght = offset+1; // Here I get payload's length
offset = 0;
// Same procedure here, but for the entire packet, including the header.
memcpy(buffer, &packet->header.pct_type, sizeof(char));
offset = sizeof(char);
memcpy(buffer + offset, &packet->header.payload_lenght, sizeof(short int));
offset += sizeof(short int);
memcpy(buffer + offset, packet->payload.path,
strlen(packet->payload.path) + 1);
offset += strlen(packet->payload.path + 1);
memcpy(buffer + offset, &packet->payload.size, sizeof(long unsigned int));
offset += (sizeof(long unsigned int));
memcpy(buffer + offset, &packet->payload.offset, sizeof(long int));
return buffer;
}
t_pct_read* deserialize_read(char* stream) {
t_pct_read* packet = malloc(sizeof(t_pct_read));
int offset;
int alloc_size;
memcpy(&packet->header.pct_type, stream, sizeof(char));
offset = sizeof(char);
memcpy(&packet->header.payload_lenght, stream + offset, sizeof(short int));
offset += sizeof(short int);
for (alloc_size = 1; (stream + offset)[alloc_size - 1] != '\0';
alloc_size++) {
packet->payload.path = malloc(alloc_size)+1;
}
memcpy(packet->payload.path, stream + offset, alloc_size+1);
offset += strlen(packet->payload.path);
memcpy(&packet->payload.size, stream + offset, sizeof(long unsigned int));
offset += (sizeof(long unsigned int));
memcpy(&packet->payload.offset, stream + offset, sizeof(long int));
return packet;
}