Dec
17

How does SortedArray copy data in and out?

By Visual C# Language Forum

I have a question about how data is copied in and out of the SortedArray generic class.  I have the following two nested structs:

    public partial class MessageHandler
    {

        public const int MAXDATALENGTH = 100;
        public enum MESSAGE_NUMBER : int { Message0=0, Message100=100, Message101=101/*etc*/};

        [StructLayout(LayoutKind.Sequential)]
        public struct HEADER
        {
            public ushort          StartOfMessage;
            public MESSAGE_NUMBER  MsgID;
            public ushort          WdCount;
            public ushort          FlagData;
            public ushort          Checksum;

        };

        [StructLayout(LayoutKind.Sequential)]
        public struct MESSAGE
        {
            public uint      Time;
            public HEADER    Header;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst=MAXDATALENGTH+1)]
            public ushort[]  Data;

        };

    }


I’m storing the MESSAGE strucs in a generic SortedList<MESSAGE_NUMBER, MESSAGE>, but the constant size array MESSAGE.Data is not being stored. Now, I thought that structs being ValueTypes, copying them into the Sorted list would copy everything, including the contents of the array Data, but it does not. I’m assuming SortedList does a A=B style copy (ie shallow). HEADER (also a struct) copies correctly, (I’m guessing) because it’s has only value type members and MESSAGE.Header being a struct (value type). I thought that the Marshal tag would cause the ushort[] to be included in the struct as a data block of ushort values, but it doesn’t seem to do this. I also tried a copy constructor to copy the contents of Data, but it didn’t work either.

In short, I believe SortedList is doing a shallow copy to move data in and out, and that the MESSAGE.Data’s contents are not being copied. How can I get C# to deep copy MESSAGE instances? Can I get a copy-constructor, or something like it, for SortedList to do deep copies.

Related posts:

  1. Declaration of a user defined struct array of fixed length in struct Hi! I'm trying to map incomming udp messages from C...
  2. C# interop services for structs and delegates These are the definitions provided in a C header file...
  3. DLL Call failure Guys,   Please help as I am pulling my hair out...
  4. gives error Method’s type signature is not PInvoke compatible. Hi experts, I have list of structs which are written...
  5. C# Struct and Shallow Copy Hola!I got 2 weird questions:1st question:In the following code I do...
Categories : C#, General SW Dev, The c's

Comments are closed.