常规套接字问题 - 将C ++结构从Java转移到C ++ [英] General Socket Question - Transferring C++ Structs from Java to C++

查看:148
本文介绍了常规套接字问题 - 将C ++结构从Java转移到C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通用套接字编程问题。

I have a general socket programming question for you.

我有一个名为Data的C结构:

I have a C struct called Data:

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

struct Attribs {
      int color;
}

我希望能够在Java中创建类似的结构,创建一个socket,使用上面的结构创建数据包,并将其发送到C ++套接字监听器。

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 it to a C++ socket listener.

你能告诉我有关序列化数据的信息(基本上是1和1) 0在包中传输)。 C ++如何读取这些数据包并重新创建结构?这样的结构如何存储在数据包中?

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.

谢谢!

推荐答案


  • 如果使用,请厌倦字节顺序二进制序列化。 Sun的JVM是Big Endian,如果你使用的是Intel x86,那么你就是一台小端机器。

  • 我会使用Java的 ByteBuffer 用于快速本机序列化。 ByteBuffers是NIO库的一部分,因此据称比ol'DataInput / OutputStreams更高的性能。

  • 特别厌倦序列化浮点数!如上所述,通过网络将所有数据传输到字符串更安全。

  • 在C ++方面,无论网络如何,在某些情况下都会有一个填充的数据缓冲区点。因此,您的反序列化代码将类似于:

    • 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)
      




      • 请注意,基本C ++类型的大小是实现定义的,因此Java和C ++中的原始类型不会直接转换。

      • 您可以使用 Google协议缓冲区。如果处理各种数据结构,我的首选解决方案。

      • 您也可以使用JSON进行序列化。

        • 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.
        • 这篇关于常规套接字问题 - 将C ++结构从Java转移到C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆