2

有人可以帮忙告诉我是否有任何可能的方法通过互联网套接字在 Windows 上运行的程序和 Unix 上运行的其他程序之间传递数据结构(即二进制格式)?

任何想法或链接到处理它的材料将不胜感激。提前感谢您的帮助,Mk

4

5 回答 5

6

查看 Google 的协议缓冲区作为序列化数据的快速方法。

于 2009-11-13T02:52:26.167 回答
4

是的,您正在寻找的是某种序列化。存在许多这样做的方法,包括:

通常,您会使用库来帮助您完成此操作。您可能还会遇到一些工具,这些工具会为您生成链接到您的程序的代码。

于 2009-11-13T02:54:34.447 回答
4

If you are against the text serialization and really want a struct, then do it like most network protocols do with "host to network" when sending and "network to host" when receiving for all fields within the struct. The idea is that all senders no matter what endianness they are always translate to network (big-endian I forget which is which). Then all receivers translate to whatever they are (might also be big-endian which is no change).

There are apis already for this. They are ntohs (network to host short for 16-bit fields) and ntohl (32-bit fields). Then of course htons and htonl.

So for a struct like this:

typedef struct
{
    unsigned char  stuff1;
    unsigned char  stuff2;
    unsigned short stuff3;
    unsigned int   stuff4;
}tFoo;

The sending code would do something like:

tFoo to_send;
to_send.stuff1 = local_stuff1;
to_send.stuff2 = local_stuff2;
to_send.stuff3 = htons(local_stuff3);
to_send.stuff4 = htonl(local_stuff4);

The receiving code would do something like:

local_stuff3 = ntohs(from.stuff3);
local_stuff4 = ntohl(from.stuff4);

Note that packing/alignment matters of the struct. You have to be weary of alignment which isn't always the same from compiler to compiler and even for the same compiler on different cpu architectures. It can even change for the datatypes themselves (an int may not be the same size from arch to arch). I attempted to demonstrate that a bit with the first two 8-bit chars, followed by a 16-bit and a 32-bit for a total of 8 bytes. You have to be certain that when you port to a different compiler/arch that you are indeed getting the correct packing/size.

For that reason most people choose serialization and probably why most people of answered with that. It is the least error prone.

Good luck.

于 2009-11-13T03:53:47.750 回答
1

Boost serialization seems like a good choice.

于 2009-11-13T02:56:50.323 回答
0

Although a binary format was requested, if you ever want to debug this kind of thing, it's really helpful to have a textual format that you can read as a human, so the suggestions of XML and maybe JSON might be appropriate. Most systems and languages have handy free libraries for reading and writing both of those, and in many, XML is built in. This also tends to mean they are well tested, integrated and performant.

于 2009-11-13T03:05:27.817 回答