[Mono-dev] Unsafe struct array reading

pablosantosluac at terra.es pablosantosluac at terra.es
Tue Sep 8 09:54:49 EDT 2009


Hi all,

I'm looking for a way to read and write array of structs from a file
(byte array).

I've the code (below) to read *one*, but I don't know how to map an
entire array.

I know there's a thousand of ways to do it with Streams, but the point
is for performance reasons I need to load them all on a single step (as
you'd do with C and fread).

Thank you

pablo



using System;
using System.Runtime.InteropServices;

namespace structIO
{
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct YourStruct
    {
        public int First;
        public long Second;
        public double Third;

        public static unsafe byte[] YourStructToBytes(YourStruct s, int
arrayLen)
        {
            byte[] arr = new byte[sizeof(YourStruct) * arrayLen];

            fixed( byte* parr = arr )
            {
                * ((YourStruct * )parr) = s;
            }

            return arr;
        }

        public static unsafe YourStruct BytesToYourStruct(byte[] arr,
int arrayLen)
        {
            if( arr.Length < (sizeof(YourStruct)*arrayLen) )
                throw new ArgumentException();

            YourStruct s;

            fixed( byte* parr = arr )
            {
                s = *((YourStruct * )parr);
            }

            return s;

        }
    }

    class structIOTest
    {
        public static void Main(string[] args)
        {
            YourStruct[] array = new YourStruct[10];

            for( int i = 0; i < array.Length; ++i )
            {
                array[i].First = 10;
                array[i].Second = (long) 10;
                array[i].Third = (double) 10;
            }

            byte[] data = YourStruct.YourStructToBytes(array[0],
array.Length);

            YourStruct result = YourStruct.BytesToYourStruct(data, 1);

        }
    }
}



More information about the Mono-devel-list mailing list