c#调c语⾔结构体转换,C#使⽤struct直接转换下位机数据的⽰
例代码
编写上位机与下位机通信的时候,涉及到协议的转换,⽐较多会使⽤到⼆进制。传统的⽅法,是将数据整体获取到byte数组中,然后逐字节对数据进⾏解析。这样操作⼯作量⽐较⼤,对于较长数据段更容易计算位置出错。
其实,对于下位机给出通讯的数据结构的情况下,可以直接使⽤C#的struct将数据直接转换。需要使⽤到Marshal。c语言struct头文件
数据结构
假定下位机(C语⾔编写)给到我们的数据结构是这个,传输⽅式为⼩端⽅式
typedef struct {
unsigned long int time; // 4个字节
float tmpr[3]; // 4*3 个字节
float forces[6]; // 4*6个字节
float distance[6]; // 4*6个字节
} dataItem_t;
⽅法1
⾸先需要定义⼀个struct:
[StructLayout(LayoutKind.Sequential, Size = 64, Pack = 1)]
public struct HardwareData
{
//[FieldOffset(0)]
public UInt32 Time; // 4个字节
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
/
/[FieldOffset(4)]
public float[] Tmpr; // 3* 4个字节
//[FieldOffset(16)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
public float[] Forces; // 6* 4个字节
//[FieldOffset(40)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
public float[] Distance; // 6*4个字节
}
然后使⽤以下代码进⾏转换
///
/
// converts byte[] to struct
///
public static T RawDeserialize(byte[] rawData, int position)
{
int rawsize = Marshal.SizeOf(typeof(T));
if (rawsize > rawData.Length - position)
throw new ArgumentException("Not enough data to fill struct. Array length from position: " + (rawData.Length - position) + ", Struct length: " + rawsize);
IntPtr buffer = Marshal.AllocHGlobal(rawsize);
Marshal.Copy(rawData, position, buffer, rawsize);
T retobj = (T)Marshal.PtrToStructure(buffer, typeof(T));
Marshal.FreeHGlobal(buffer);
return retobj;
}
///
/// converts a struct to byte[]
///
public static byte[] RawSerialize(object anything)
{
int rawSize = Marshal.SizeOf(anything);
IntPtr buffer = Marshal.AllocHGlobal(rawSize);
Marshal.StructureToPtr(anything, buffer, false);
byte[] rawDatas = new byte[rawSize];
Marshal.Copy(buffer, rawDatas, 0, rawSize);
Marshal.FreeHGlobal(buffer);
return rawDatas;
}
注意这⾥我使⽤的⽅式为LayoutKind.Sequential,如果直接使⽤LayoutKind.Explicit并设置FieldOffset会弹出⼀个诡异的错误System.TypeLoadException:“Could not load type 'ConsoleApp3.DataItem' from assembly 'ConsoleApp3, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because it contains an object field at offset 4 that is incorrectly aligned or overlapped by a non-object field.”。
⽅法2
提⽰是对齐的错误,这个和编译的时候使⽤的32bit和64位是相关的,详细数据封送对齐的操作我不就详细说了,贴下代码。
//强制指定x86编译
[StructLayout(LayoutKind.Explicit, Size = 64, Pack = 1)]
public struct DataItem
{
[MarshalAs(UnmanagedType.U4)]
[FieldOffset(0)]
public UInt32 time; // 4个字节
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3, ArraySubType = UnmanagedType.R4)]
[FieldOffset(4)]
public float[] tmpr; // 3* 4个字节
[FieldOffset(16)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6, ArraySubType = UnmanagedType.R4)]
public float[] forces; // 6* 4个字节
[FieldOffset(40)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6, ArraySubType = UnmanagedType.R4)]
public float[] distance; // 6*4个字节
}
强制指定x64编译没有成功,因为数据对齐后和从下位机上来的数据长度是不符的。
⽅法3
微软不是很推荐使⽤LayoutKind.Explicit,如果⾮要⽤并且不想指定平台的话,可以使⽤指针来操作,当然,这个需要unsafe。var item = RawDeserialize(tail.ToArray(), 0);
unsafe
{
float* p = &item.forces;
for (int i = 0; i < 6; i++)
{
Console.WriteLine(*p);
p++;
}
}
[StructLayout(LayoutKind.Explicit, Size = 64, Pack = 1)]
public struct DataItem
{
[FieldOffset(0)]
public UInt32 time; // 4个字节
[FieldOffset(4)]
public float tmpr; // 3* 4个字节
[FieldOffset(16)]
public float forces; // 6* 4个字节
[FieldOffset(40)]
public float distance; // 6*4个字节
}
⽅法4
感觉写起来还是很⿇烦,既然⽤上了unsafe,就⼲脆直接⼀点。
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public unsafe struct DataItem
{
public UInt32 time; // 4个字节
public fixed float tmpr[3]; // 3* 4个字节
public fixed float forces[6]; // 6* 4个字节
public fixed float distance[6]; // 6*4个字节
}
这样,获得数组可以直接正常访问,不再需要unsafe了。
总结
数据解析作为上下位机通讯的常⽤操作,使⽤struct直接转换数据可以⼤⼤简化⼯作量。建议还是使⽤LayoutKind.Sequential来进⾏封送数据,有关于数据在托管与⾮托管中的转换,可以详细看看微软有关互操作的内容。
以上代码在.NET 5.0下编译通过并能正常执⾏。
补充
注意上⾯的前提要求是字节序为⼩端字节序(⼀般计算机都是⼩端字节序),对于⼤端字节序发送过来的数据,需要进⾏字节序转换。我到⼀处代码写的很好:
public static class FooTest
{
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Foo2
{
public byte b1;
public short s;
public ushort S;
public int i;
public uint I;
public long l;
public ulong L;
public float f;
public double d;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
public string MyString;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Foo
{
public byte b1;
public short s;
public ushort S;
public int i;
public uint I;
public long l;
public ulong L;
public float f;
public double d;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
public string MyString;
public Foo2 foo2;
}
public static void test()
{
Foo2 sample2 = new Foo2()
{
b1 = 0x01,
s = 0x0203,
S = 0x0405,
i = 0x06070809,
I = 0x0a0b0c0d,
l = 0xe0f101112131415,
L = 0x161718191a1b1c,
f = 1.234f,
d = 4.56789,
MyString = @"123456789", // null terminated => only 9 characters!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论