开发者

General Socket Question - Transferring C++ Structs from Java to C++

开发者 https://www.devze.com 2023-01-10 05:23 出处:网络
I have a general socket programming question for you. I have a C struct called Data: struct data { double speed;

I have a general socket programming question for you.

I have a C struct called Data:

struct data {
      double speed;
      double length; 
      char carName[32];
      struct Attribs;
}

struct Attribs {
      int color;
}

I would like to be able to create a similar structure in Java, create a socket, create the data packet with the above struct, and send开发者_StackOverflow社区 it to a C++ socket listener.

What can you tell me about having serialized data (basically, the 1's and 0's that are transferred in the packet). How does C++ "read" these packets and recreate the struct? How are structs like this stored in the packet?

Generally, anything you can tell me to give me ideas on how to solve such a matter.

Thanks!


  • Be weary of endianness if you use binary serialization. Sun's JVM is Big Endian, and if you are on an Intel x86 you are on a little endian machine.
  • I would use Java's ByteBuffer for fast native serialization. ByteBuffers are part of the NIO library, thus supposedly higher performance than the ol' DataInput/OutputStreams.
  • Be especially weary of serializing floats! As suggested above, its safer to transfer all your data to character strings across the wire.
  • On the C++ side, regardless of the the networking, you will have a filled buffer of data at some point. Thus your deserialization code will look something like:

size_t amount_read = 0;
data my_data;
memcpy(buffer+amount_read, &my_data.speed, sizeof(my_data.speed))
amount_read += sizeof(my_data.speed)
memcpy(buffer+amount_read, &my_data.length, sizeof(my_data.length))
amount_read += sizeof(my_data.length)
  • Note that the sizes of basic C++ types is implementation defined, so you primitive types in Java and C++ don't directly translate.
  • You could use Google Protocol buffers. My preferred solution if dealing with a variety of data structures.
  • You could use JSON for serialization too.


The basic process is:

  • java app creates some portable version of the structs in the java app, for example XML
  • java app sends XML to C++ app via a socket
  • C++ app receives XML from java app
  • C++ app creates instances of structs using the data in the XML message
0

精彩评论

暂无评论...
验证码 换一张
取 消