I\'m converting a delphi app to C#. There are a bunch of packed records, and according to a similar question I asked a few weeks ago, it would be better to convert to classe
You need to specify sequential layout and a pack value of 1.
[StructLayout(LayoutKind.Sequential, Pack = 1)]
Since there are not textual members, you need not specify CharSet
. And you should let the compiler calculate the size of the struct. Now, having specified this you will be able to read the entire record into memory, and then blit it directly onto this C# struct. Like so:
Testrec ReadRecFromStream(Stream stream)
{
byte[] buffer = new byte[Marshal.SizeOf(typeof(Testrec))];
stream.Read(buffer, 0, buffer.Length);
GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
try
{
return (Testrec)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(Testrec));
}
finally
{
handle.Free();
}
}
However, you said that you were going to read on member at a time and assign to the corresponding field in the C# struct. In that case there's no need to seek binary layout equivalence since you won't be making any use of that. If you are going read one member at a time then you do not need a StructLayout
attribute. You don't need to declare any unused members. You can convert the Delphi date time values into the appropriate C# data types at the point of input and so on.
So, you do need to make up your mind as to whether or not you are going to seek binary layout equivalence of these structures.