This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

RE: sending structure containing a pointer to another structure over TCP socket


Hi Abid,
 
Let's suppose you had this:
 
struct Second;
 
struct First
{
  short value;
  char* s;
  Second* second;
};
 
struct Second
{
  int a;
  char b;
  long c;
};
 
And let's assume that on your platform, char is 1 byte, short is 2 byte, int is 4 byte, and long is 8 byte.  And let's assumet that pointers much be 4-byte aligned, and int must be 4-byte aligned, and long must be 8-byte aligned.
 
If you want to send First over the wire, and you want to include Second, what you should do is write a send routine, and a receive routine.  I presume you use the hton and ntoh inside the low level data types Send and Recieve routines, which you'd have written.
 
void Send(int fd, First const& first)
{
  SendInt16(fd, first.value);
  SendCharArray(fd, size, first.s);
  Send(fd, *(first.second));
};
 
void Send(int fd, Second const& second)
{
  SendInt32(fd, second.a); 
  SendInt8(fd, second.b); 
  SendInt64(fd, second.c);
};
 
void Receive(int fd, First& first)
{
  ReceiveInt32(fd, first.value);
  ReceiveCharArray(fd, first.s);
  first.second = new Second;
  Receive(fd, *(first.second));
}
 
void Recieve(int fd, Second& second)
{
  RecieveInt32(fd, second.a); 
  RecieveInt8(fd, second.b); 
  RecieveInt64(fd, second.c);
}
 
This is C++.  You can use something similar for C (using pointers instead of references, and distinguished names).  Don't forget to use ntoh (network Big Endian byte order to host byte order) and hton (host byte order to network Big Endian byte order) functions!
 
Alternatively, you can "flatten" your data structures into a textual representation, such as XML, and reconstitute it on the remote side.  Some situations, textual format may be preferable over some canonical binary format.
 
Notice that we have avoided your pointer problem.  We've also avoided sending along garbage intrastructure padding bytes and trailing structure alignment bytes, and we've avoided Big Endian / Little Endian problems, and we've avoided the issues caused by different platforms (OS and C/C++ compiler) having different sized fundamental data types.
 
Yet another alternative, is to work with IDL such as CORBA, or RPC, to use as a higher level language designed to address this exact problem domain.  But that may be swatting a mosquito with a nuclear warhead, depending on your needs.
 
HTH,
--Eljay
 


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]