What is the best way for Copying 'mydata' to 'sample_a'?
I expect to get 4 in sample_a.data_array[ 1 ]. That value is p[ 9 ].
I plan to use this for TCP/UDP packet communication.
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct SampleA
{
public int data1;
public int data2;
public unsafe fixed char data_array[3];
public int data3;
}
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
short bytesize = 15;
byte[] mydata = new byte[bytesize];
unsafe
{
fixed (byte* p = mydata)
{
// data1
p[0] = 1;
// data2
p[4] = 2;
// data_array
p[8] = 3;
p[9] = 4;
p[10] = 5;
// data3
p[11] = 6;
}
// Copy 'mydata' to 'sample_a'
IntPtr intptr = Marshal.AllocHGlobal(bytesize);
Marshal.Copy(mydata, 0, intptr, bytesize);
SampleA sample_a = (SampleA)Marshal.PtrToStructure(intptr, typeof(SampleA));
Marshal.FreeHGlobal(intptr);
// I want to get 4 in a1
int a1 = (int)sample_a.data_array[1];
}
}
