Windows 到 iPhone 二进制文件
将二进制文件从 Windows 传递到 iPhone 是否安全,这些文件的编写方式如下:
std::ostream stream = // get it somehow
stream.write(&MyHugePODStruct, sizeof(MyHugePODStruct));
读取方式如下:
std::istream stream = // get it somehow
stream.read(&MyHugePODStruct, sizeof(MyHugePODStruct));
虽然 MyHugePODStruct
的定义相同?如果没有,有什么方法可以使用标准库(包括 c++11)或安全地升压来序列化它?有没有更干净的方法,因为它看起来像是一段不可移植的代码?
Is it safe to pass binary files from Windows to iPhone that are written like:
std::ostream stream = // get it somehow
stream.write(&MyHugePODStruct, sizeof(MyHugePODStruct));
and read like:
std::istream stream = // get it somehow
stream.read(&MyHugePODStruct, sizeof(MyHugePODStruct));
While the definition of MyHugePODStruct
is the same? if not is there any way to serialize this with either standard library (c++11 included) or boost safely? is there more clean way to this, because it seems like a non portable piece of code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,有很多原因。首先,这不会编译,因为您必须将
char *
传递给read
和write
。其次,这甚至不能保证在一个平台上工作,因为该结构可能包含填充(但即使在同一平台上,不同编译版本的代码之间的填充本身也可能有所不同)。接下来,需要考虑影响许多基元类型的 64/32 位问题(例如,long double
在 x86 上填充为 12 字节,但在 x64 上填充为 16 字节)。最后但并非最不重要的一点是字节序(尽管我不确定 iOS 字节序是什么)。简而言之,不,不要这样做。
您必须根据其数据类型单独序列化每个结构成员。
您可能想查看 Boost.serialization,尽管我没有这方面的经验。
No, for many reasons. First off, this won't compile, because you have to pass a
char *
toread
andwrite
. Secondly, this isn't guaranteed to work on even one single platform, because the structure may contain padding (but that itself may differ between different among differently compiled versions of the code, even on the same platform). Next, there are 64/32-bit issues to consider which affect many of the primitive types (e.g.long double
is padded to 12 bytes on x86, but to 16 bytes on x64). Last but not least there's endianness (though I'm not sure what the iOS endianness is).So in short, no, don't do that.
You have to serialize each struct member separately, and according to its data type.
You might like to check out Boost.serialization, though I have no experience with it.