转换Delphi指针和stream.Read到c#

时间:2016-08-11 13:38:29

标签: c# bytearray delphi-7 filestream

我正在尝试将旧的binary files应用转换为packed records。它通过我在BInfoRec写的record来做一些事情。但是,只有FileStream.Read packed records保证在文件中并首先显示。其他人可能会或可能不会在那里,他们的顺序是未知的。我特别难以使用一种方法。它通过if获取正在读取的字节数,并将其读入StartP = packed record x:SmallInt; y:SmallInt; end; InfoP = packed record Ycoord:double; Xcoord:double; //other vars here end; HeadP = packed record NumP:DWORD; SizeStruct:DWORD; SizePoStruct:DWORD; //other vars here end; BInfoRec = packed record StructNum : WORD ; in_size : WORD ; //other variables here end; var tStream:TFileStream; bInfo:BInfoRec; RestOfBFile:Pointer; sizeofRest:Integer; Function LoadBFile(FileName:String):Boolean; var sizeread:Integer; begin Try LoadBFile:=False; tStream:=TFileStream.Create(Filename,fmOpenRead ); sizeofRest:=tStream.Size-Sizeof(bInfo); sizeread:=tStream.Read(bInfo,Sizeof(bInfo)); if sizeread = Sizeof(bInfo) then begin //best way to convert this? RestOfBFile:=AllocMem(sizeofRest); sizeread:=tStream.Read(RestOfBFile^,sizeofRest); if SizeofRest= SizeRead then LoadBFile:=True; end; tStream.Free; except LoadBFile:=False; tStream.Free; end; end; 之一。然后,在第一个[Serializable()] [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)] public struct StartP { public short x; public short y; } [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)] public struct InfoP { public double Ycoord; public double Xcoord; //other vars here } [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)] public struct HeadP { public UInt32 NumP; public UInt32 SizeStruct; public UInt32 SizePoStruct; //other vars here } [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)] public struct BInfoRec { public ushort StructNum; public ushort in_size; } BInfoRec bInfo; int sizeOfRest; private Boolean LoadBFile(string fileName) { int sizeRead; byte[] buffer = new byte[Marshal.SizeOf(bInfo)]; try { using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None)) { sizeOfRest = (int)stream.Length - Marshal.SizeOf(typeof(BInfoRec)); sizeRead = stream.Read(buffer, 0, Marshal.SizeOf(typeof(BInfoRec))); if (sizeRead == Marshal.SizeOf(typeof(BInfoRec))) { //what goes here?? if (sizeOfRest == sizeRead) { return true; } } } } catch (Exception ex) { return false; } } 语句中(在delphi版本中),它在堆上分配内存,并执行与以前相同的操作,但将其读入指针。我试图找出解决这个问题的最佳方法,但我并不是Delphi的专家。

德尔福代码:

BinaryReader

C#(我到目前为止):

list-style

我正在考虑创建一个未知大小的新字节数组,并使用display:inline-block将该文件的其余部分读入该数组,然后只检查其大小。不确定它是否是最佳方式?

1 个答案:

答案 0 :(得分:1)

它是任意大小的内存块。我没有看到你有很多选项,而不是字节数组。是的,您可以分配非托管内存(例如使用Marshal.AllocHGlobal),但这很不方便。

所以,是的,如果我是你,我会分配一个字节数组,并将内容读入其中。