From: Piranha on 23 Mar 2010 10:36 I´m trying to memcpy a set of data into a struct and I´m not sure whether I´m doing it right. Let´s say I have a struct like this. struct MyStruct { int value1; std::string value2; float value3; }; MyStruct MyData = {1,"Test",0.1}; First I´m converting the struct to char* (to send it over a socket, or something like that). char* x = (char*)&MyData; send(socket,x,sizeof(MyStruct),0); Now I receive the data from the socket as an array of char[] char buffer[1000]; long rc = recv(socket,buffer,1000,0); Then I do MyStruct MyReceivedData; memcpy((void*)&MyReceivedData,(void*)&buffer,sizeof(MyStruct)); Am I doing this right, or did I get the syntax wrong and/or is there some trap hidden, such as losing part of the data in case the conversions MyStruct -> char* -> char[] -> void* -> MyStruct don´t work?
From: Ben Bacarisse on 23 Mar 2010 11:40 Piranha <eu_piranha(a)gmx.net> writes: > I´m trying to memcpy a set of data into a struct and I´m not sure > whether I´m doing it right. > Let´s say I have a struct like this. > > struct MyStruct > { > int value1; > std::string value2; > float value3; > }; > > MyStruct MyData = {1,"Test",0.1}; > > First I´m converting the struct to char* (to send it over a socket, or > something like that). > > char* x = (char*)&MyData; > send(socket,x,sizeof(MyStruct),0); > > Now I receive the data from the socket as an array of char[] > > char buffer[1000]; > long rc = recv(socket,buffer,1000,0); > > Then I do > > MyStruct MyReceivedData; > memcpy((void*)&MyReceivedData,(void*)&buffer,sizeof(MyStruct)); > > Am I doing this right, or did I get the syntax wrong and/or is there > some trap hidden, such as losing part of the data in case the > conversions > MyStruct -> char* -> char[] -> void* -> MyStruct > don´t work? That's right they don't -- at least not the way you are doing it. Copying just the bits in MyData won't work unless the types are plain old data types and both sides of the connection represent the structure in exactly the same way. (Even when this does work it is fragile and best avoided). You need to take control of the whole conversion process starting with how you want the data to be represented in transit. This is quite a large topic, but a simple solution is to copy what one does for IO: Decide how you'd print a MyStruct in such a way that you can read it back (i.e. design << and << operations) but then use these to generate and interpret the bytes you transmit over the connection. Useful terms to search for include "serialising data" and "marshaling". -- Ben.
|
Pages: 1 Prev: difference between char *a="abc" and char b[]="abc" Next: Write 64bit? |