【发布时间】:2016-06-27 10:33:47
【问题描述】:
我主要使用 C 语言,并且很长一段时间没有使用过类。我正在尝试使用其他人创建的一些类函数,但我无法使 deserialize() 函数工作。我理解它的作用,但我一生都无法弄清楚如何调用这个函数。我在下面提供了函数以及我如何尝试调用它们。
//Creates a packet
packet::packet(int t, int s, int l, char * d){
type = t;
seqnum = s;
length = l;
data = d;
}
// This function serializes the data such that type, seqnum, length, and data values are placed
// in a char array, spacket, and separated by a single space; that is, spacket contains the serialized data
void packet::serialize(char * spacket){
cout << "data: " << endl << endl;
sprintf (spacket, "%d %d %d %s", type, seqnum, length, data);
}
// This function deserializes a char array, spacket, which is the result of a call to serialize
void packet::deserialize(char * spacket){
char * itr;
itr = strtok(spacket," ");
char * null_end;
this->type = strtol(itr, &null_end, 10);
itr = strtok(NULL, " ");
this->seqnum = strtol (itr, &null_end, 10);
itr = strtok(NULL, " ");
this->length = strtol (itr, &null_end, 10);
if(this->length == 0){
data = NULL;
}
else{
itr = strtok(NULL, "");
for(int i=0; i < this->length; i++){ // copy data into char array
this->data[i] = itr[i];
}
}
}
这就是我试图让它发挥作用的方法:
packet *test = new packet(1, 4, 4, message); //message is a *char with the data
test->serialize(sendbuf); //this works correctly
packet *test2 = new packet(0,0,0, NULL); //I am not sure if I need to be creating a new packet for the deserialized information to get placed into
test->deserialize(sendbuf); //results in a segmentation fault currently
我只是不明白如何调用 deserialize(),我创建了一个数据包并对其进行了序列化,这部分工作正常,但我不明白如何反转它。我需要先创建一个空的数据包对象吗?如果是这样,怎么做?我已经尝试过多种方式,但我无法让它发挥作用。我知道这是非常基本的,但就像我说的那样,我已经有几年没有上课了。我花了很长时间才让序列化工作,但我已经尝试了所有我能想到的反序列化方法并且卡住了。
【问题讨论】:
标签: c++ function class object serialization