English 中文(简体)
基于TCP的跨应用程序内存大小(typname)的C/C++可靠性
原标题:C/C++ reliability of memcpy sizeof(typname) cross application over TCP
  • 时间:2010-10-15 12:41:35
  •  标签:
  • c++
  • byte

我一直在我目前正在进行的一个项目中进行一些文件IO,到目前为止,我已经使用以下快速方便的方法读取了整个数据块:

struct Header { ... };
class Data { ... };
// note that I have not used compiler directives to pack/align/order bytes
// partly because I don t know how to.

Header _header;
Data _data;
std::ifstream fin(filename);
fin.read((char*)&_header, sizeof(Header));
fin.read((char*)&_data, sizeof(Data));
fin.close();

我的问题是,对于每台编译器和每台不同的计算机,假设字节以相同的方式对齐和排序是否可以?

例如,如果我采用Header结构,在linux上编译一个客户端程序,在windows上编译一一个服务器程序。字节的顺序是否相同,这样就不会出现双向接收和发送问题?

最佳回答

不,这根本不能保证。有一个特定的网络字节顺序,据我所知,WinAPI和POSIX都提供本地到网络的翻译功能。此外,还可以使用编译器指令控制对齐。但你必须明确地处理好这两件事。

问题回答

这是一个已经解决的问题,避免重新发明那个轮子。XML是机器在互联网上相互交流的通用语言。如果带宽是个问题,那就去找谷歌的protobuf吧。它有许多语言绑定,很好地支持C++。

好吧,在一般情况下当然不是。有些平台有不同的字节顺序(endianness)相比其他。

此外,在64位平台上,一些常见的整数类型(如size_t)的大小可能与您预期的不同。所有的C保证是sizeof(long)>=sizeof(短)>=sizeof(char),因此甚至可能存在一个反常的平台,其中long、short和char的大小都相同。

实际上,如果您的两个平台都是Intel,并且您的操作系统都是32位(或都是64位),那么您可能还可以。不过,最好查看编译器的指令,以便更好地确定对齐和排序。遗憾的是,C和C++在这方面还不如Ada那么擅长。您可以使用标准编码,如ASN.1来解决这个问题,但ASN.1是一种几乎总是比疾病更糟糕的治疗方法。





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签