在c#开发过程中,想要实现c语言中,数组和结构体之间任意转换,该方式在实现协议上特别有用
1.c#结构体字节对齐
使用[StructLayout(LayoutKind.Sequential, Pack = 1)]实现
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct test
{
public UInt16 aa;
public byte bb;
public UInt16 cc;
public byte dd;
public byte ee;
}
2:数组转换到结构体
byte[] buf = new byte[256];
byte[] buf2 = new byte[256];
test Header = new test();
buf[0] = 0x11;
buf[1] = 0x22;
//数组转结构体,字节对齐
IntPtr ptr3 = Marshal.AllocHGlobal(256);//分配非托管内存空间
Marshal.Copy(buf, 0, ptr3, buf.Length);//将数组数组拷贝到非托管内存指针
Header = (test)Marshal.PtrToStructure(ptr3, typeof(test));
Marshal.FreeHGlobal(ptr3);//释放内存
3:结构体转数组
//结构体转数组
IntPtr ptr1 = Marshal.GetIUnknownForObject(Header);
Marshal.Copy( ptr3,buf2, 0, 7);//将数组数组拷贝到非托管内存指针