gpt4 book ai didi

c - 用 C 序列化包

转载 作者:行者123 更新时间:2023-11-30 15:55:56 24 4
gpt4 key购买 nike

我是新来的,我会喜欢你的帮助。我尝试序列化和反序列化一个包(在套接字中使用它),结果不是我期望的结果,但我找不到错误。这是代码。

typedef struct {
int32_t size;
char data[1024];
} t_socket_buffer;

typedef struct {
int16_t payloadLength;
int8_t type;
char *path;
} ReadRequestPackage;

序列化函数

t_socket_buffer *Open_serializer(ReadRequestPackage *ReadPackage){
char data[1024];
t_socket_buffer *stream = malloc(sizeof(t_socket_buffer));
int8_t offset = 0, tmp_size = 0;


memcpy(data, &ReadPackage->payloadLength, tmp_size = sizeof(int16_t));

offset = tmp_size;
memcpy(data + offset,&ReadPackage->type, tmp_size = sizeof(int8_t));


offset+= tmp_size;
memcpy(data + offset, ReadPackage->path,tmp_size = strlen(ReadPackage->path)+1);


stream->size = offset + tmp_size;
memcpy(stream->data, data,strlen(data)+1);

return stream;

}

反序列化函数

    ReadRequestPackage *Open_deserializer(t_socket_buffer *stream)
{
ReadRequestPackage *ReadPackage = malloc(sizeof(ReadRequestPackage));
int32_t offset = 0, tmp_size = 0;

memcpy(&ReadPackage->payloadLength,stream->data,tmp_size = sizeof(int16_t));

offset = tmp_size;
memcpy(&ReadPackage->type, stream->data + offset, tmp_size = sizeof(int8_t));

offset += tmp_size;
for(tmp_size = 1; (stream->data + offset)[tmp_size-1]!='\0';tmp_size++);
ReadPackage->path = malloc(tmp_size);
memcpy(ReadPackage->path, stream->data + offset, tmp_size);



return ReadPackage;

}

当我用这个 main() 测试它时

int main (void){
ReadRequestPackage *pqt1 = malloc(sizeof(ReadRequestPackage));
ReadRequestPackage *pqt2;

t_socket_buffer *stream;
pqt1->path=malloc(sizeof("directory"));
strcpy(pqt1->path,"directory");
pqt1->payloadLength = strlen("directory")+1+sizeof(int8_t);
pqt1->type = 1;

stream = Open_serializer(pqt1);
pqt2 = Open_deserializer(stream);
printf("path 1: ");
puts(pqt1->path);
printf("path 2: ");
puts(pqt2->path);
printf("\ntype1:%d ",pck1->type);
printf("\ntype2:%d ",pck2->type);
printf("\nize:%d ",pck1->payloadLength);
printf("\nsize:%d ",pck2->payloadLength);

return 1;
}

结果不一样,但应该是一样!

非常感谢!

最佳答案

memcpy(stream->data, data,strlen(data)+1);

这条线没有做你认为它在做的事情。 data 不是字符串。

顺便说一句,您是否考虑过使用合适的序列化库?

关于c - 用 C 序列化包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11604948/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com