首页 > 解决方案 > C中的数据(反)序列化

问题描述

我想知道是否有人可以帮助我解决我的问题。在客户端,我有一个链表,其中每个项目都包含一个整数。假设我附加了 5 个整数(比如说 1、2、3、4、5)。我检查了一下,创建整数并将其附加到链表的例程没问题。之后,我想通过下面的代码序列化链表:

typedef struct ser_buff_ {
  void *b;
  int size; // total size of the buffer
  int next; // length of the contained data 
}ser_buff_t;

void serialize_linkedlist(table_t *table, ser_buff_t *b){
  table_entry_t *head = table->next;
  while(head){
    int temp = head->data;
    serialize_data(b, (char*)&temp, sizeof(int));
    head = head->next;
  }
  unsigned int sentinel = 0xFFFFFFFF;
  serialize_data(b, (char*)&sentinel, sizeof(unsigned int)); // mark the tail
}

table 指的是链表中的第一项,b 是我要序列化链表的缓冲区。如您所见,调用了函数 serialize_data()。功能如下:

void serialize_data(ser_buff_t *b, char *data, int nbytes){
  if(b == NULL) assert(0);
  ser_buff_t *buff = b;
  int available_size = buff->size - buff->next;
  int isResize = 0;

  while(available_size < nbytes){
    buff->size *= 2;
    available_size = buff->size - buff->next;
    isResize = 1;
  }
  if(isResize == 0){
    memcpy((char*)buff->b + buff->next, data, nbytes);
    buff->next += nbytes;
    return;
  }
  buff->b = realloc(buff->b , buff->size);
  memcpy((char*)buff->b + buff->next, data, nbytes);
  buff->next += nbytes;
  return;
}

序列化链表后,我通过以下代码将缓冲区发送到服务器:

ret = write(data_socket, b, b->next);

在服务器端,我通过套接字接收序列化缓冲区。

ret = read(data_socket, b, 128);

我确定b->next在客户端小于128。从客户端接收到序列化数据后,服务器将其传递给反序列化函数:

void de_serialize_linkedlist(ser_buff_t *b, table_t *table){
  int i = 1;
  unsigned int sentinel = 0;
  while(i){
    de_serialize_data((char*)&sentinel, b, sizeof(unsigned int));
    if(sentinel == 0xFFFFFFFF){
      break;
    }
    else{
      serialize_buffer_skip(b, sizeof(unsigned int)* (-1));
      de_serialize_data((char*)&i, b, sizeof(int));
      add(table, i);
    }
  }
}

在这个函数内部,还有另一个函数 de_serialize_data() 被调用:

void de_serialize_data(char *dest, ser_buff_t *b, int nbytes){
  if(!b || !b->b) assert(0);
  if(!nbytes) return;
  if((b->size - b->next) < nbytes) assert(0);
  memcpy((char*)dest, (char*)b->b + b->next, nbytes);
  b->next += nbytes;
}

但是当我到达线路时我遇到了错误

memcpy((char*)dest, (char*)b->b + b->next, nbytes);

我认为b->b不可访问,这不是我的期望。谁能帮帮我。

标签: cserializationrpc

解决方案


推荐阅读