0

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

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

结果是不一样的,他们应该!

非常感谢你!

4

1 回答 1

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

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

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

于 2012-07-22T23:56:37.450 回答