Skip to content

Resource Classes

This tutorial explains how to save/load objects from classes that extends cx::Resource.

Android example

Let’s start with an Android class with a few data fields, including a battery object. I will omit constructor and methods, we’re only interested on the fields.

class Battery{
private:
    char type;
    float level;
...
};

class Android{
private:
    std::string name;
    Batery      batery;
    bool        active;
...
};

We want both classes to be resources that can be read/written from/to data streams. So the first thing to do is to make them inherit from the class cx::Resource:

class Battery: public cx::Resource{
...
};

class Android: public cx::Resource{
...
};

The class cx::Resource has two pure virtual private methods that we must override: read and write. Let’s start with the Battery class. The most important is to read and write the same information in the same order (a read/write protocol):

class Battery: public cx::Resource{
...
private:
    // Save battery to output
    void write(cx::DataOutputStream& output) const{
        output.writeInt8(type);    // first a 8 bits integer
        output.writeFloat(level);  // then a float
    }
    // Load battery from input
    void read(cx::DataInputStream& input){
        type  = input.readInt8();  // first a 8 bits integer
        level = input.readFloat(); // then a float
    }
};

We do the same for the Android, which has a battery. Since the Battery class is a Resource, it can now be read/written as we do for the primitive types:

class Android: public cx::Resource{
...
private:
    // Save android to output
    void write(cx::DataOutputStream& output) const{
        output << name << battery << active;
    }
    // Load android from input
    void read(cx::DataInputStream& input){
        input >> name >> battery >> active;
    }
};

Finally, somewhere else on your program you can read/write androids through data streams, like this:

try{
    // save an android to file
    Android droid;
    cx::FileOutputStream outStream("droid.bot");
    outStream << droid;
    outStream.close();

    // load the anddroid from the file
    cx::FileInputStream inStream("droid.bot");
    inStream >> droid;
    inStream.close();
}catch(std::exception& e){
    std::cout << "Exception caught: " << e.what() << std::endl;
}

Conclusion

Serialization of classes is simple, just inherit from cx::Resource and implement the read and write methods. Always remember to follow the same protocol when reading and writing.
On the next page we’ll see how to create custom pipeline components (producers, consumers and filters).


Index ||  Basic Streaming <<  Resource Classes  >>  Custom Pipeline