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

旧街凉风 提交于 2019-12-01 07:14:21
  • 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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!