《[2017年整理]C#中结构体和字节流互相转换》由会员分享,可在线阅读,更多相关《[2017年整理]C#中结构体和字节流互相转换(3页珍藏版)》请在金锄头文库上搜索。
1、因为程序必须要和 C+开发的程序通信,而通信数据的是结构体的转化后的字节流,那么就要求 C#能够顺利的将字节流转换为 C#结构体。1. 定义与 C+对应的 C#结构体代码/C+结构体struct tagCheakUser char userName12;char pwd32;/对应的 C#结构体StructLayout( LayoutKind.Sequential,Pack=1)public struct CheckUserMarshalAs( UnmanagedType.ByValTStr,SizeConst=12)public string userName;MarshalAs(Unman
2、agedType .ByValTStr,SizeConst=32)public string pwd;在 C+的头文件定义中,使用了 #pragma pack 1 字节按 1 对齐,所以C#的结构体也必须要加上对应的特性,LayoutKind.Sequential 属性让结构体在导出到非托管内存时按出现的顺序依次布局,而对于 C+的 char数组类型,C#中可以直接使用 string 来对应,当然了,也要加上封送的特性和长度限制。2. 结构体与 byte的互相转换代码/convert structure T to byte public static byte ConvertStructToB
3、ytes(object objStruct)/get the size of structureint size = Marshal.SizeOf(objStruct);/define buffer arraysbyte buffer = new bytesize;/Alloc unmanaged memory and Copy structure to unmanaged memoryIntPtr ipStruct = Marshal.AllocHGlobal(size);Marshal.StructureToPtr(objStruct, ipStruct, false);/Copy to
4、the byte arrayMarshal.Copy(ipStruct, buffer, 0, size);/Free unmanaged memoryMarshal.FreeHGlobal(ipStruct);return buffer;/convert byte array to sturcturepublic static TR ConvertBytesToSturct(byte datas)/get size of sturctureint size = Marshal.SizeOf(typeof(TR);/can not be convertif (datas.Length (bDatas);Console.WriteLine(User:0 Pwd:1, ckUser1.userName, ckUser1.pwd); Console.ReadKey();这样,就能有效的和 C+通讯了。