我想将字节数组(大小38)转换为此结构。
当我将代码编辑为 公共字节[] arrayAxis; 该代码运行非常困难。
请帮助...谢谢!
[System.Serializable]
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct SInfo
{
public byte STX;
public short Length;
public short ID;
public byte CMD;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)]
public float[] arrAxis;
//public float AxisX;
//public float AxisY;
//public float AxisZ;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public float[] arrQuat;
//public float QuaternionX;
//public float QuaternionY;
//public float QuaternionZ;
//public float QuaternionW;
public byte State;
public short State2;
public byte CRC;
}
我编写并使用了此功能。
public T FromByteArray<T>(byte[] _array)
{
BinaryReader _reader = new BinaryReader(new MemoryStream(_array));
GCHandle handle = GCHandle.Alloc(_array, GCHandleType.Pinned);
T theStructure = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
handle.Free();
return theStructure;
}
答案 0 :(得分:1)
结构的大小为122字节,因为浮点数为4字节。因此arrAxis = 4 x 12和arrQuat = 4 x16。下面的代码经过了测试。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Runtime.InteropServices;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
SInfo s = new SInfo();
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(s));
Marshal.StructureToPtr(s, ptr, true);
byte[] buffer = new byte[Marshal.SizeOf(s)];
Marshal.Copy(ptr, buffer, 0, Marshal.SizeOf(s));
Test test = new Test();
SInfo sinto = test.FromByteArray<SInfo>(buffer);
}
}
public class Test
{
public T FromByteArray<T>(byte[] _array)
{
BinaryReader _reader = new BinaryReader(new MemoryStream(_array));
GCHandle handle = GCHandle.Alloc(_array, GCHandleType.Pinned);
T theStructure = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
handle.Free();
return theStructure;
}
}
[System.Serializable]
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct SInfo
{
public byte STX;
public short Length;
public short ID;
public byte CMD;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)]
public float[] arrAxis;
//public float AxisX;
//public float AxisY;
//public float AxisZ;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public float[] arrQuat;
//public float QuaternionX;
//public float QuaternionY;
//public float QuaternionZ;
//public float QuaternionW;
public byte State;
public short State2;
public byte CRC;
}
}
答案 1 :(得分:1)
SizeConst
表示定长数组或定长数组中元素的数量。 要导入的字符串中的字符数(不是字节)。
因此,您可能希望将其分别设置为3和4,而不是12和16-然后该结构的大小将为38个字节。