Marshalling data to a char array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • EnlightenedOne
    New Member
    • May 2010
    • 1

    Marshalling data to a char array

    Hey there I have a data structure with a set size of 40 I want to marshall the data from an object into an array of characters for simplistic transmission of data. I am aware of serialization but only familiar with it in higher languages, I am stuck using c.

    My question is this. How do I point to an individual character value of the unmarshalled object in order to marshall it into a character array I can throw down the socket pipe?

    char dataToSend[40];
    I assume I need a loop but have no method to break up host control item struct into an assignable single character form.
    dataToSend = (char*)&hostCon trolItem; throws an error.
    dataToSend = (char[40]*)&hostControlI tem; throws an error.
    dataToSend = (char*[40])&hostControlIt em; throws an error.

    In pseudo code I need
    for (int i = 0; i <40; i++)
    {
    dataToSend[i] = (char*)&hostCon trolItem.asBina ry([i]);
    }

    Is there an inbuilt method to convert an object to a character array? google was useless!
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    The is no built in method. Simplistically you could use memcpy. However there are a few things to be cautious of.
    • Structures often have padding, that is data that appears between the structure members so that the members have the correct alignment in memory. Strictly you do not need to transmit this padding, it is never normally accessible to the program so over a low band width link or in a speed critical application you would not want to send that data.
    • If the structure contains any pointers transmitting them to another process/computer will be pointless because they will be meaningless to the other computer/process. You need to transmit what the point to.
    • If the other computer has different endianess to the transmitting computer then copying the values like that will result in incorrect data transfer. You will have all the right byte values but in the wrong places.


    Generally it is never a good idea to translate you structures structure directly onto a communication medium. You need to marshal it and unmarshal itat the other end.

    Marshalling is not terribly hard, you just make sure you are dealing with basic types only and marshal those types into the data stream in a specific way that is platform independent. That way any platform can unmarshal the data correctly.

    So for your structure I would recomend writing a function that takes a const struct pointer and a char * pointer to the buffer (or unsigned char * preferably since the data is raw bytes) and for each individual member of the structure marshals that data into the buffer provided.

    Comment

    Working...