C# byte[]、struct、intptr等的相互转换
2016-07-28 15:37
513 查看
1.struct byte[]互相转换
//struct转换为byte[] public static byte[] StructToBytes(object structObj) { int size = Marshal.SizeOf(structObj); IntPtr buffer = Marshal.AllocHGlobal(size); try { Marshal.StructureToPtr(structObj, buffer, false); byte[] bytes = new byte[size]; Marshal.Copy(buffer, bytes, 0, size); return bytes; } finally { Marshal.FreeHGlobal(buffer); } } //byte[]转换为struct public static object BytesToStruct(byte[] bytes, Type type) { int size = Marshal.SizeOf(type); IntPtr buffer = Marshal.AllocHGlobal(size); try { Marshal.Copy(bytes, 0, buffer, size); return Marshal.PtrToStructure(buffer, type); } finally { Marshal.FreeHGlobal(buffer); } }
[b]2.Intptr、byte[]互相转换[/b]
//IntPtr转byte[] IntPtr y;//初始化 略 byte[] ys = new byte[yLength]; Marshal.Copy(y, ys, 0, yLength);
//byte[]转换为Intptr public static Intptr BytesToIntptr(byte[] bytes) { int size = bytes.Length; IntPtr buffer = Marshal.AllocHGlobal(size); try { Marshal.Copy(bytes, 0, buffer, size); return buffer; } finally { Marshal.FreeHGlobal(buffer); } }
至于struct和Intptr转换,完全可以参考上面的函数
相关文章推荐
- C# 关键字
- C#实现字符串倒叙方法整理
- C# 根据IP获取省市
- C#重写和覆写区别
- 【C#基础】(int),int.Parse,Convert.ToInt32三种转换的区别
- C#也能动态生成Word文档并填充数据
- LINQ数据查询 Resharper插件使用
- C#常用的命名规则汇总
- C# 实现打开和关闭可执行文件
- List和数组转换
- 《C#高级编程》读书笔记(十三):应用程序域
- C#环形缓冲区(队列)完全实现
- C# 控制台捕获关闭事件的代码
- C# FTP远程服务器返回错误:(550) 文件不可用(例如,未找到文件,无法访问文件)
- c#——Winform TreeView 赋值(id,name,pid)类型数据
- C# 滚动字幕的实现
- c# 枚举
- C# DEV,treelist,实现分层及TreeList常用用法
- C#未将对象引用设置到对象的实例
- C# 创建、载入XML文件学习笔记