C# How to get data from the 2-Dimensional byte Array which is member of the structure

101 views Asked by At

In structure, a member was declared as 2-Dimensional array which name as myData and layout to 2*3.

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct myStruct
{
    [MarshalAs(UnmanageType.ByValArray, SizeConst = 2 * 3)]
    public byte[,] myData;
}

I declare a myStruct variable and name as testStruct. After the data was written to myData. I can't to read the data from myData.

case1. string myDataString = Encoding.UTF8.GetString(testStruct.myData[0]);

ErrorMsg: The number of index in [] incorrect, must be 2.

case2. string myDataString = Encoding.UTF8.GetString(testStruct.myData[0,0]);

ErrorMsg: Can not form 'byte' convert to 'byte[]'

case3.

byte temp = new byte[3];
temp = testStruct.myData[0];

ErrorMsg: The number of index in [] incorrect, must be 2.

case4. string myDataString = testStruct.myData[0].ToString;

ErrorMsg: The number of index in [] incorrect, must be 2.

case5. string myDataString = testStruct.myData[0,0].ToString;

ErrorMsg: Can not convert method ToString convert to string.

All of above cases I tried were show errors. How can I extract the data and save as byte[] or string ??

Is there has wrong with declare myData Array ??

I expect the data can be read 1-Dimensional per times. It is convenient to parsing the data from Multi-Dimensional Array by loop.

1

There are 1 answers

4
JonasH On

I'm going to assume that the actual goal is serialization/deserialization of the array. Most tools cannot handle 2D arrays, so you need to convert it to a 1D array. You can do this by copying the data to a new 1D array:

var source = new byte[3, 2];
var target = new byte[6];
Buffer.BlockCopy(source, 0, target, 0, 6);

However, it may be a better alternative to use a 1D array in the first place, and write your own indexer to treat it as 2D data.

public struct MyMatrix
{
    public int Width { get; }
    public int Height { get; }
    public byte[] Data = new byte[6];

    public MyMatrix(int width, int height)
    {
        Width = width;
        Height = height;
        Data = new byte[width * height];
    }

    public byte this[int x, int y] { 
        get => Data[y * Width + x];
        set => Data[y * Width + x] = value;
    }
}

Note that the example lacks range checks for each index, so myMatrix[5, 0] would not throw an exception.

See How to base64 encode/decode if you want to convert the array to a string.