title: Sending a C++ struct over UDP in Java
body: <p>I'm a C++ programmer and have a need to set up some UDP communications between a java android app and the C++ server running on a PC.</p>
  
  <p>I have structure that I need to receive on the PC that consists of the following:</p>
  
  <pre><code>int
  int
  float
  </code></pre>
  
  <p>Unfortunately I'm totally at a loss as to how I can do this with Java.</p>
  
  <p>I need to create a DatagramPacket but the constructor only takes a byte array.  Now with C++ this would be an easy cast from a struct to a char*.  However casting like this is not possible with Java.  </p>
  
  <p>I've create a simple class that has the above fields in it.  That seems to be fine.  My remaining issue is how to turn that into a byte array.  Can anyone help a Java noob on this front?</p>
  
  <p>Cheers!</p>
  
  <p>Edit: I've created a function in the class that does the following</p>
  
  <pre><code>        public byte[] GetBytes() throws IOException
          {
              ByteArrayOutputStream   byteOut = new ByteArrayOutputStream();
              DataOutputStream        dataOut = new DataOutputStream( byteOut ); 
              dataOut.writeInt( Integer.reverseBytes( int1) );
              dataOut.writeInt( Integer.reverseBytes( int2 ) );
              dataOut.writeFloat( float1 );
  
              return byteOut.toByteArray();
          }
  </code></pre>
  
  <p>Is there a better way to do this?</p>
  
  <p>I'd rather not use the google protocol buffer mentioned in Steve's answer because, while its interesting, it would require too many changes to other platform implementations that I'd really rather not do.</p>