[2017年整理]C#中结构体和字节流互相转换

上传人:豆浆 文档编号:909872 上传时间:2017-05-21 格式:DOCX 页数:3 大小:26.31KB
返回 下载 相关 举报
[2017年整理]C#中结构体和字节流互相转换_第1页
第1页 / 共3页
[2017年整理]C#中结构体和字节流互相转换_第2页
第2页 / 共3页
[2017年整理]C#中结构体和字节流互相转换_第3页
第3页 / 共3页
亲,该文档总共3页,全部预览完了,如果喜欢就下载吧!
资源描述

《[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+通讯了。

展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > 行业资料 > 其它行业文档

电脑版 |金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号