• 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)原创或者转载,如若转载请务必注明出处,谢谢合作!
  • 相关阅读:
    菜单栏与功能工具栏
    信息与编码
    opencv颜色体系认知
    团队-科学计算器-开发文档
    CSS3动画
    Font Awesome 4.0.3 字体图标完美兼容IE7
    Bootstrap+Thinkphp3.2+Auth认证+jquery-validator后台
    Wordpress主题中常用代码总结
    Wordpress 常用代码解释
    wordpress一些常用代码
  • 原文地址:https://www.cnblogs.com/YinaPan/p/streambytsstruct.html
Copyright © 2020-2023  润新知