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;
            }

        }

  • 相关阅读:
    htmilunit-- 针对抓取js生成的数据
    httpClient get方式抓取数据
    post方式的数据抓取
    利用win10自带的系统配置禁止开机启动项和程序
    linq中怎么实现多条件关联的左右连接
    win10提示管理员已阻止你运行此应用,如何强制运行
    远程连接SQL Server 2014遇到的问题和解决
    eclipse中删除多余的tomcat server
    resultMap之collection聚集
    empty()和remove()的区别
  • 原文地址:https://www.cnblogs.com/evlon/p/865272.html
Copyright © 2011-2022 走看看