sdd1208
sdd1208

Reputation: 125

Memcpy and Structures

I'm working to copy the following structure to a byte array to send over a named pipe. I've found that since switching from a byte array that I had given a static definition, to a vector because my host length will be of varying lengths.

Here is the outline of my structure:

        USHORT version;                                 // Header Version
    USHORT type;                                    // IPVersion
    USHORT count;                                   // Number of IP addresses of remote system
    USHORT length;                                  // Header Length (1)
    BYTE SysConfigLocIP[4];
    BYTE SysConfigRemoteIP[4];
    USHORT lengthHost;
    std::vector<BYTE>HostName;

later, after filling the structure I copy it to a byte like so:

    BYTE Response[sizeof(aMsg)]
    memcpy(response, &aMsg, sizeof(aMsg))

I find that my array is vector is holding the correct information for the host when I inspect the container during a debug. However, after the copy to the Response byte array, I'm finding the data that has been copied is drastically different. Is this a valid operation, if so, what can I do correctly copy the data from my vector the BYTE array. If not, what are other strategies I can use to dynamically size the structure to send the hostnames? Thank you for taking the moment of time to read my question, and I appreciate any feedback.

Upvotes: 0

Views: 262

Answers (3)

Arun
Arun

Reputation: 20383

I'm working to copy the following structure to a byte array to send over a named pipe.

named pipe (or other forms of inter-process or inter-processor communication) does not understand your struct, neither do they understand vector. They just operate on the concept of byte-in-byte-out. It is up to you, the programmer, to assign meaning to those bytes.

As suggested, please read on serialization. Try starting at http://en.wikipedia.org/wiki/Serialization. If permitted you can use the Boost solution, http://www.boost.org/doc/libs/1_55_0/libs/serialization/doc/index.html, but I would still encourage you to understand the basics first.

As an exercise, first try transferring a vector<int> from sender to receiver. The number of elements in the vector must not be implicitly known by the receiver. Once you achieve that, migrating from int to your struct would be trivial.

Upvotes: 2

Neil Kirk
Neil Kirk

Reputation: 21803

99% of the time in C++ there is no reason to use memcpy. It breaks classes. Learn about copy constructors and std::copy and use them instead.

Upvotes: 0

David Schwartz
David Schwartz

Reputation: 182789

That memcpy will only work for POD (plain old data) types. A vector is not POD. Instead, write code to put each byte in the buffer exactly where it needs to be. Don't rely on "magic".

Upvotes: 1

Related Questions