【发布时间】:2016-03-03 17:52:17
【问题描述】:
我正在将一个 delphi 应用程序转换为 C#。有一堆打包的记录,根据我几周前问的一个类似问题,最好转换为类。但是,有人告诉我需要将它们转换为结构,我可以使用一些帮助。我将使用BinaryReader 从文件中读取并将值分配给结构内的字段。
*注意,我正在读取的文件是使用 Delphi 和打包记录制作的。
这是一个示例结构:
德尔福:
Testrec = packed record
now: TDateTime;
MinLat: longint;
MinLong: longint;
Firsttime: TDateTime;
MinAlt: single;
MinFirst: single;
MinDepth: single;
MinSpeed: single;
MinBot: single;
res3: single;
res4: single;
res5: single;
res6: single;
MaxLat: longint;
MaxLong: longint;
Lasttime: TDateTime;
MaxAlt: single;
MaxFirst: single;
MaxDepth: single;
MaxSpeed: single;
MaxBot: single;
res9: single;
res10: single;
res11: single;
res12: single;
DataFlags: longint;
ReviewFlags: longint;
res13: longint;
FirstPost: longint;
end;
这是我的 C# 版本:
public struct Testrec
{
double now;
int MinLat;
int MinLong;
double Firsttime;
float MinAlt;
float MinFirst;
float MinDepth;
float MinSpeed;
float MinBot;
float res3;
float res4;
float res5;
float res6;
int MaxLat;
int MaxLong;
double Lasttime;
float MaxAlt;
float MaxFirst;
float MaxDepth;
float MaxSpeed;
float MaxBot;
float res9;
float res10;
float res11;
float res12;
int DataFlags;
int ReviewFlags;
int res13;
int FirstPost;
}
我需要做一个StructLayout、Size和CharSet吗?
编辑:这是有关读取二进制文件的相关delphi代码:
Testrec Header;
HeaderSize = 128;
RampStream:=TFileStream.Create(FilePath,fmOpenReadWrite OR fmShareExclusive );
RampStream.Read(Header,HeaderSize);
StartTime:=Header.Firsttime;
EndTime:=Header.Lasttime;
以下是我设置二进制阅读器的方法:
RampStream = new BinaryReader(new FileStream(RampName, FileMode.Open, FileAccess.ReadWrite, FileShare.None));
【问题讨论】:
-
你的结构超过了推荐的 16 个字节:stackoverflow.com/questions/1082311/…
-
该结构可能超过了 16 个字节的限制,但这并不能回答问题,也不相关。他的问题主要是如何在 C# 中声明结构,使其不包含填充字节,即具有 bte 对齐。 FWIW,我会以任何语言传递这样的结构作为参考。
-
@RudyVelthuis 作为引用传递意味着被调用者可以修改它。
-
是的,在 C# 中确实如此。 C# 不能有 const 参数有点问题。但如果速度是一个问题,我仍然会通过参考。