B
Beorne
I have to read a stucture from a stream. The stream could be a memory
stream or a file stream.
Supposing the structure to read is InputStruct:
[StructLayout(LayoutKind.Sequential,Pack=1)]
unsafe public struct InputStruct
{
public int Int1;
public int Int2;
public fixed double Val[100];
}
I can use the following:
BinaryReader br = new BinaryReader(stream);
//reading a byte array of the struct dimension
byte[] buff = br.ReadBytes(Marshal.SizeOf(typeof(InputStruct)));
// Protecting the buffer from GarbageCollector
GCHandle handle = GCHandle.Alloc(buff, GCHandleType.Pinned);
// shaping the structure on the buffer
InputStruct inputStruct =
(InputStruct)Marshal.PtrToStructure(handle.AddrOfPinnedObject(),
typeof(InputStruct));
// Giving back memory to the GarbageCollector
handle.Free();
This works well.
But I have to read a native C structure shaped like this:
[StructLayout(LayoutKind.Sequential,Pack=1)]
unsafe public struct InnerStruct
{
public int I;
public double D;
}
[StructLayout(LayoutKind.Sequential,Pack=1)]
unsafe public struct InputStruct
{
public int Int1;
public int Int2;
public fixed double InnerStruct[100]; //!!!!
}
In C# it is not possible to declare a fixed length field in a
structure with anything except primitive types.
I could read the struct by a sequence of BinaryReader.ReadXy() but
this is too time consuming.
How could I read in a single pass a structure containing structures?
Thanks.
stream or a file stream.
Supposing the structure to read is InputStruct:
[StructLayout(LayoutKind.Sequential,Pack=1)]
unsafe public struct InputStruct
{
public int Int1;
public int Int2;
public fixed double Val[100];
}
I can use the following:
BinaryReader br = new BinaryReader(stream);
//reading a byte array of the struct dimension
byte[] buff = br.ReadBytes(Marshal.SizeOf(typeof(InputStruct)));
// Protecting the buffer from GarbageCollector
GCHandle handle = GCHandle.Alloc(buff, GCHandleType.Pinned);
// shaping the structure on the buffer
InputStruct inputStruct =
(InputStruct)Marshal.PtrToStructure(handle.AddrOfPinnedObject(),
typeof(InputStruct));
// Giving back memory to the GarbageCollector
handle.Free();
This works well.
But I have to read a native C structure shaped like this:
[StructLayout(LayoutKind.Sequential,Pack=1)]
unsafe public struct InnerStruct
{
public int I;
public double D;
}
[StructLayout(LayoutKind.Sequential,Pack=1)]
unsafe public struct InputStruct
{
public int Int1;
public int Int2;
public fixed double InnerStruct[100]; //!!!!
}
In C# it is not possible to declare a fixed length field in a
structure with anything except primitive types.
I could read the struct by a sequence of BinaryReader.ReadXy() but
this is too time consuming.
How could I read in a single pass a structure containing structures?
Thanks.