reinterpret_cast'ing a byte array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • joem86
    New Member
    • Oct 2008
    • 2

    reinterpret_cast'ing a byte array

    I figured the subject would get everyone's attention. So when dealing with sockets, you receive an array of unsigned char's, also known as bytes. One way to interpret data from those bytes is to make a class with all your needed fields (or struct, it doesn't matter), and do something like this:

    Code:
    MyClass *translatedData = reinterpret_cast<MyClass*>(&rawBytesReceivedFromSocket);
    Obviously this is not ideal. I have to check that the payload is sane before doing something like this. The bytes' structure has to line up with my class exactly. Also, something just doesn't sit well with me, when essentially I'm doing a c-style translation in c++ clothing (if that makes any sense). Not very secure either, treating raw-bytes this way.There has to be a better, OO way. Any ideas?

    Joe
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Well the way I choose is this, assuming like me you may be receiving several different messages/formats then
    • You have a 2 level class hierarchy, the base class is abstract and contains a load of protected helper methods as well as a few public interface methods.
    • Some of the protected methods are methods to extract and insert 1, 2 or 4 byte integers, strings and floats from the buffer
    • The interface methods include methods to verify the message is formatted correctly as well as a single method to handle the message.
    • There is 1 subclass for each message you might receive.
    • There is a static public factor method on the base class that given a buffer will create a class of the correct type to hold it. It returns a pointer to the base class.
    • Each subclass has specific knowledge of the things that particular message carries and provides methods that call the helper functions to extract the data.
    • You implement something like the visitor pattern to allow handling of each message.


    So when you receive a buffer you call the factory method to create a class of the correct type and this returns a base class pointer to it. The class stores the raw data of the buffer you then verify the message format and discard it if invalid.

    You pass the message (the pointer) to the message handling process. This process calls the message handling method on the base class pointer which results in a callback with a sub-class pointer. You can now access all the data in the message and deal with it as appropriate.


    Instead of pointers it would be a good idea to use a handle template class (handle design pattern). As I was using C++/CLR (.NET in C++) where handles are a built in part of the language and are the reference of choice I did not need to do this.

    Comment

    Working...