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.
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:
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.
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.