c++ - 调用使用字符数组的类函数 (C++)

标签 c++ function class object serialization

我主要使用 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(),我创建了一个数据包并将其序列化并且该部分工作正常,但我不明白如何反转它。我需要先创建一个空数据包对象吗?如果是这样,如何?我尝试过多种方式,但我无法让它工作。我知道这是非常基础的,但就像我说的,我已经有几年没有上过课了。我花了很长时间才开始序列化工作,但我已经尝试了所有我能想到的反序列化方法,但还是卡住了。

最佳答案

@Pongjazzle,

我同意 Sam 的观点,即类设计需要改进。但是,我认为您可以弄清楚。假设 sendbuf 可以保存所有序列化的数据包数据,您可能希望通过这种方式来测试您的代码。

packet *test = new packet(1, 4, 4, message);
test->serialize(sendbuf);

packet *test2 = new packet(0,0,0, NULL); // results in a segmentation fault currently (which is expected as the attempts to access a location referred to by a null pointer in this->data (i.e., NULL based on the object instantiation code)
test->deserialize(sendbuf);

将其更改为:

packet *test2 = new packet(0,0,0, newmessage); // assign a valid buffer
test2->deserialize(sendbuf);  // Now fill's in the values and buffer from serialized content.

关于c++ - 调用使用字符数组的类函数 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35952788/

相关文章:

c++ - 类的大小、成员函数的大小、继承类的大小?

java - 我如何从 libgdx 中的另一个类调用方法

c++ - 搜索集合数组的更快方法

javascript - 向函数添加自定义属性

javascript - 使用 jquery 在最近的单元格 (td) 中查找元素?

c++ - C++ 中的谓词是什么?

c++ - c++代码中的意外输出,未获得预期结果

c++ - 理解问题: Precompiled headers & include usage

c++ - 从 Visio UML 图创建 C++ 代码

c++ - 如何定义全局函数来检查边界?