用于“序列化”的reinterpret_cast接收端的数据、字节顺序和对齐方式
如果我们有一个 POD 结构说 A,我这样做:
char* ptr = reinterpret_cast<char*>(A);
char buf[20];
for (int i =0;i<20; ++i)
buf[i] = ptr[i];
network_send(buf,..);
如果接收端远程盒子不一定是相同的硬件或操作系统,我可以安全地执行此操作以“反序列化”:
void onRecieve(..char* buf,..) {
A* result = reinterpret_cast<A*>(buf); // given same bytes in same order from the sending end
“结果”始终有效吗? C++标准规定POD结构,reinterpret_cast的结果应该指向第一个成员,但这是否意味着即使接收端是不同的平台,实际的字节顺序也将是正确的?
If we have a POD struct say A, and I do this:
char* ptr = reinterpret_cast<char*>(A);
char buf[20];
for (int i =0;i<20; ++i)
buf[i] = ptr[i];
network_send(buf,..);
If the recieving end remote box, is not necessarily same hardware or OS, can I safely do this to 'unserialize':
void onRecieve(..char* buf,..) {
A* result = reinterpret_cast<A*>(buf); // given same bytes in same order from the sending end
Will the 'result' always be valid? The C++ standard states with POD structures, the result of reinterpret_cast should point to the first member, but does it mean the actual byte order will be correct also, even if the recieving end is a different platform?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,你不能。您只能将“向下”转换为
char*
,而永远不能返回到对象指针:代码中:
简而言之:如果您想要一个对象,则必须< em>有一个对象。如果随机内存位置确实不是对象(即,如果它不是所需类型的实际对象的地址),则不能假装它是对象。
No, you cannot. You can only ever cast "down" to
char*
, never back to an object pointer:In code:
In a nutshell: If you want an object, you have to have an object. You cannot just pretend a random memory location is an object if it really isn't (i.e. if it isn't the address of an actual object of the desired type).
您可以考虑为此使用模板并让编译器为您处理它
You may consider using a templatefor this and letting the compiler handle it for you