zoukankan      html  css  js  c++  java
  • 从struct到byte[]之RawFormatter

        public partial class Form1 : Form
        
    {
            
    public Form1()
            
    {
                InitializeComponent();
            }


            
    private void Form1_Load(object sender, EventArgs e)
            
    {
                Demo d 
    = new Demo();
                d.a 
    = 5;
                d.b 
    = 10;
                d.c 
    = new byte[]{1,2,3};
                d.s 
    = "123";
                
    byte[] buf = RawFormatter.RawSerialize(d);

                

                MessageBox.Show(
    "aaa");
                
            }

        }


        [StructLayout(LayoutKind.Sequential,Pack
    =1,CharSet=CharSet.Ansi)]
        
    struct Demo
        
    {
            
    public byte a;
            
    public int b;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst 
    = 3)]
            
    public byte[] c;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst 
    = 5)]
            
    public string s;
        }


        
    public class RawFormatter
        
    {
            
    public static byte[] RawSerialize(object anything)
            
    {
                
    int rawsize = Marshal.SizeOf(anything);
                IntPtr buffer 
    = Marshal.AllocHGlobal(rawsize);
                Marshal.StructureToPtr(anything, buffer, 
    false);
                
    byte[] rawdatas = new byte[rawsize];
                Marshal.Copy(buffer, rawdatas, 
    0, rawsize);
                Marshal.FreeHGlobal(buffer);
                
    return rawdatas;
            }


            
    public static object RawDeserialize(byte[] rawdatas, Type anytype)
            
    {
                
    int rawsize = Marshal.SizeOf(anytype);
                
    if (rawsize > rawdatas.Length)
                    
    return null;
                IntPtr buffer 
    = Marshal.AllocHGlobal(rawsize);
                Marshal.Copy(rawdatas, 
    0, buffer, rawsize);
                
    object retobj = Marshal.PtrToStructure(buffer, anytype);
                Marshal.FreeHGlobal(buffer);
                
    return retobj;
            }

        }

  • 相关阅读:
    Selenium+unittest(4)生成html报告带截图
    Selenium+unittest(2)配置模块介绍
    python+requests+unittest(1)接口自动化测试框架结构介绍
    Selenium+unittest(1)web自动化整体框架介绍
    App自动化测试
    robotframework自动化测试框架搭建及问题汇总
    QTP11完美破解小笔记
    Loadrunner11完美破解小笔记
    【转】微信小程序专项测试
    【转】如何测试微信应用号
  • 原文地址:https://www.cnblogs.com/evlon/p/865272.html
Copyright © 2011-2022 走看看