简体   繁体   中英

C# splitting array of data into several properties

I would like to get an opinion of what would be the best approach how to tackle my problem. I have some ideas but they are far from perfect in my opinion and maybe someone can suggest a nice and clean way how to do this.

The picture below illustrates my general code structure 在此处输入图片说明

I have a communications module that writes data to an array consisting of data bytes. And i want to keep the structure there as it is, because then it is a flexible fully GUI independent solution. Just to explain my reason behind this further - the data structure represents a physical memory of an external hardware unit (MCU).

After that I need to split up that data into properties. Meaning that I have several properties that are bound to elements in GUI giving them data. Thus I want each property take data from specific region in array as example index 100:104.

The problematic part for me is how to bind these properties to the array in the mentioned way? The binding needs to be two way.

I am not sure if it is what you need, but looks like you can use such approach:

You can create some structure that realize properties:

[StructLayout(LayoutKind.Explicit, Size = 11, Pack = 0)]
public struct MyStructure
{
    public string StringFromBytes
    {
        get
        {
            if (ByteArrayField == null || ByteArrayField.Length == 0)
            {
                return string.Empty;
            }

            return Utilitites.BytesToString(ByteArrayField);
        }
    }

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] [FieldOffset(0)] public byte[] ByteArrayField;
    [MarshalAs(UnmanagedType.U2)] [FieldOffset(8)] public ushort WordField;
    [MarshalAs(UnmanagedType.I1)] [FieldOffset(10)] public sbyte dBm0;
}

Here we have a structure that consist of 11 bytes. This structure has a property that makes some manipulation with data. You need to determine where a field starts (FieldOffset()) and how data should be interpreted (eg UnmanagedType.U2 - 2-byte unsigned integer).

When you receive bytes array from your device, you can easily transform that array to your structure:

    public static T ToStructure<T>(this byte[] bytes) where T : struct
    {
        GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
        var stuff = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
        handle.Free();
        return stuff;
    }

Usage:

byte[] responseBytes = Utilitites.GetResponseFromDevice();
MyStructure response = responseDecodedBytes.ToStructure<MyStructure>();

Hope that will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM