C#元帅数组构造

时间:2018-11-01 16:53:38

标签: c# arrays struct marshalling

我正在尝试使用Marshal将数组复制到结构:

[StructLayout(LayoutKind.Sequential, Pack = 1,Size = 14)]
public struct RDShifterGearDecrease
{
    [MarshalAs(UnmanagedType.U4,SizeConst =4)]
    public UInt32 PosReduceGear;
    [MarshalAs(UnmanagedType.U4, SizeConst = 4)]
    public UInt32 PosReturnCenter;
    [MarshalAs(UnmanagedType.U2, SizeConst = 2)]
    public UInt16 BlipTimeBeforeDecreaseGear;
    [MarshalAs(UnmanagedType.U2, SizeConst = 2)]
    public UInt16 TimeoutGearDecrease;
    [MarshalAs(UnmanagedType.U2, SizeConst = 2)]
    public UInt16 TimeoutReturnCenter;
}

我的数组是:

[0]=0;
[1]=1;
[2]=5;
[3]=4;
...
[13]=0;

我用来复制的方法是:

 private static T FillObjectWithData<T>(byte[] arr)
 {
      T str = default(T);
       try
       {
           int size = Marshal.SizeOf(str);
           IntPtr ptr = Marshal.AllocHGlobal(size);
           Marshal.Copy(arr, 0, ptr, size);
           str = (T)Marshal.PtrToStructure(ptr, str.GetType());
           Marshal.FreeHGlobal(ptr);
       }
       catch (Exception e)
       {
       }
       return str;
 }

例如,第一个变量PosReduceGear的值我想为0x0154 = 340,但是给了我0x04050100 = 67436800

我了解原因,并希望避免在复制之前操纵数组。我可以在结构上做些什么?

0 个答案:

没有答案