zoukankan      html  css  js  c++  java
  • c#结构体和字节数组的转换、字节数组和stream的转换

    本文由博主(YinaPan)原创,转载请注明出处:http://www.cnblogs.com/YinaPan/p/streambytsstruct.html

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    using System.IO;
    using System.Runtime.InteropServices;
    
    class Converter {
        public static Byte[] StructToBytes(Object structure) {
            Int32 size = Marshal.SizeOf(structure);
            IntPtr buffer = Marshal.AllocHGlobal(size);
            try {
                Marshal.StructureToPtr(structure, buffer, false);
                Byte[] bytes = new Byte[size];
                Marshal.Copy(buffer, bytes, 0, size);
                return bytes;
            }
            finally {
                Marshal.FreeHGlobal(buffer);
            }
        }
        public static Object BytesToStruct(Byte[] bytes, Type strcutType) {
            Int32 size = Marshal.SizeOf(strcutType);
            IntPtr buffer = Marshal.AllocHGlobal(size);
            try {
                Marshal.Copy(bytes, 0, buffer, size);
                return Marshal.PtrToStructure(buffer, strcutType);
            }
            finally {
                Marshal.FreeHGlobal(buffer);
            }
        }
    
        public static byte[] StreamToBytes(Stream stream) {
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);
            // 设置当前流的位置为流的开始
            stream.Seek(0, SeekOrigin.Begin);
            return bytes;
        }
    
        public static Stream BytesToStream(byte[] bytes) {
            Stream stream = new MemoryStream(bytes);
            return stream;
        }
    }
    MyStruct pack = new MyStruct();
    pack = (MyStruct)Converter.BytesToStruct(Converter.StreamToBytes(stream), pack.GetType());
    本文由博主(YinaPan)原创或者转载,如若转载请务必注明出处,谢谢合作!
  • 相关阅读:
    w3c盒子模型与ie盒子模型
    前端入门
    连接数据库好用工具
    前端开发工具
    刚发现的取色工具
    使用val()另一个妙用------选中select/checkbox/radio的值
    z-index的妙用
    react生命周期函数
    react中虚拟dom的diff算法
    React中的虚拟DOM
  • 原文地址:https://www.cnblogs.com/YinaPan/p/streambytsstruct.html
Copyright © 2011-2022 走看看