0

In c# I created a MemoryMappedViewAccessor and a structure. I want to read from the accessor into the structure. The structure contains all fixed length fields corresponding to the layout of the original file. I use only C# Integral numeric types (i.e. byte, ushort, uint, ulong) for all fields because acessor.Read<T>(struct) requires that no field be a reference type however, some of the data from the original file must be larger than the largest value type available to me. I cannot use any arrays (i.e. byte[]) since no field can be a reference type.

damarp
  • 1
  • 3

1 Answers1

5

You're looking for fixed size buffers.

You can create a structure that contains a number of bytes inline:

struct Structure
{
    unsafe fixed byte largeField[256];
}

They are not actual arrays, C# stores all those bytes inline in the struct. The accesses to its elements are simply pointer offsets. It's unsafe, since it is not a real array, there is no bounds checking, you can overrun the stack – see this question.

It gets compiled roughly to the equivalent of:

struct Structure
{
    [StructLayout(LayoutKind.Sequential, Size = 256)]
    [CompilerGenerated]
    [UnsafeValueType]
    public struct <largeField>e__FixedBuffer
    {
        public byte FixedElementField;
    }

    [FixedBuffer(typeof(char), 128)]
    public <largeField>e__FixedBuffer largeField;
}

As you can see the result contains no reference types, so you can use that with MemoryMappedViewAccessor.

V0ldek
  • 9,623
  • 1
  • 26
  • 57