Help reading fixed structure from Stream

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.
 
N

Nicholas Paldino [.NET/C# MVP]

The only option I can see to this would be to expand the array out in
the structure, like so:

[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 InnerStruct InnerStruct00;
public InnerStruct InnerStruct01;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top