简体   繁体   English

跨编译器读写原始对象到磁盘(istream)

[英]Reading and writing raw object to disk (istream) across compilers

I've been porting over some old legacy code. 我一直在移植一些旧的遗留代码。 It is 15 years old and used to compile with some old Borland compiler. 它已有15年的历史,并用于使用某些旧的Borland编译器进行编译。 We are not able to compile the old code due to missing dependencies/compiler. 由于缺少依赖项/编译器,我们无法编译旧代码。

We have something like this: 我们有这样的事情:

class SegmentParameterDataRecord
{
private:
  int32_t parameterId;
  double value;

public:
  SegmentParameterDataRecord() : parameterId(0), value(0.0) {}
  int32_t & getParameterId() { return parameterId; }
  double & getValue() { return value; }

  void read(std::istream & in);
  void write(std::ostream & out);
};

Note the read and write methods. 请注意readwrite方法。 Here they are: 他们来了:

void SegmentParameterDataRecord::read(std::istream & in)
{
  in.read((char *) this, sizeof(*this));
}

void SegmentParameterDataRecord::write(std::ostream & out)
{
  out.write((char *) this, sizeof(*this));
}

This brought up some concerns to me. 这给我带来了一些担忧。 Note that the old code casts to a char * and processes the data as raw bytes of memory. 注意,旧代码强制转换为char *并将数据作为内存的原始字节进行处理。 I believe I am running into problems when I ported this code over to the latest MinGW. 我相信将代码移植到最新的MinGW时会遇到问题。

1) Is it possible that the internal memory representation of SegmentParameterDataRecord is different across compilers, and thus it would be problematic to write the SegmentParameterDataRecord on one compiler (15-year old Borland) and then read it on another compiler (recent MinGW)? 1) SegmentParameterDataRecord的内部存储器表示SegmentParameterDataRecord在不同的编译器中是否可能不同,因此将SegmentParameterDataRecord write一个编译器(已使用15年的Borland)并在另一个编译器(最近的MinGW)上read它是有问题的吗?

2) Is it possible that sizeof(SegmentParameterDataRecord) could be different from a 15-year old Borland compiler to today's MinGW? 2) sizeof(SegmentParameterDataRecord) )是否有可能与15岁的Borland编译器与当今的MinGW不同?

3) How likely is this possibility? 3)这种可能性有多大?

Is it possible that sizeof(SegmentParameterDataRecord) could be different from a 15-year old Borland compiler to today's MinGW? sizeof(SegmentParameterDataRecord)可能与使用15年的Borland编译器与当今的MinGW不同吗?

This is definitely possible. 这绝对是可能的。 In fact, sizeof(int) can be different across compilers and across machines. 实际上,在编译器和机器之间, sizeof(int)可能不同。 For example, on a 32-bit machine, sizeof(int) is often 4 bytes, but on a 64-bit machine, sizeof(int) can be 8 bytes. 例如,在32位计算机上, sizeof(int)通常为4个字节,但在64位计算机上, sizeof(int)可以为8个字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM