zoukankan      html  css  js  c++  java
  • C#结构体数组间的转化

    转自:http://developer.51cto.com/art/200908/143779.htm

    解决C#结构体数组间的转化问题的由来:在写C#TCP通信程序时,发送数据时,如果是和VC6.0等写的程序通信的话,很多的都是传送结构体,在VC6.0中可以很方便的把一个char[]数组转换为一个结构体,而在C#却不能直接把byte数组转换为结构体,要在C#中发送结构体,可以按以下方法实现:

    (1)解决C#结构体数组间的转化之定义结构体:

    1. //命名空间  
    2. using System.Runtime.InteropServices;  
    3.  
    4. //注意这个属性不能少  
    5. [StructLayoutAttribute(  
    6. LayoutKind.Sequential,  
    7. CharSet=CharSet.Ansi,Pack=1)]  
    8. struct TestStruct  
    9. ...{  
    10. public int c;  
    11. //字符串,SizeConst为字符串的最大长度  
    12. [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]  
    13. public string str;  
    14. //int数组,SizeConst表示数组的个数,在转换成  
    15. //byte数组前必须先初始化数组,再使用,初始化  
    16. //的数组长度必须和SizeConst一致,例test = new int[6];  
    17. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]  
    18. public int[] test;  

    (2)解决C#结构体数组间的转化之byte数组转结构体:

    1. /**//// <summary>  
    2. /// byte数组转结构体  
    3. /// </summary>  
    4. /// <param name="bytes">byte数组</param>  
    5. /// <param name="type">结构体类型</param>  
    6. /// <returns>转换后的结构体</returns>  
    7. public static object BytesToStuct(byte[] bytes,Type type)  
    8. ...{  
    9. //得到结构体的大小  
    10. int size = Marshal.SizeOf(type);  
    11. //byte数组长度小于结构体的大小  
    12. if (size > bytes.Length)  
    13. ...{  
    14. //返回空  
    15. return null;  
    16. }  
    17. //分配结构体大小的内存空间  
    18. IntPtr structPtr = Marshal.AllocHGlobal(size);  
    19. //将byte数组拷到分配好的内存空间  
    20. Marshal.Copy(bytes,0,structPtr,size);  
    21. //将内存空间转换为目标结构体  
    22. object obj = Marshal.PtrToStructure(structPtr, type);  
    23. //释放内存空间  
    24. Marshal.FreeHGlobal(structPtr);  
    25. //返回结构体  
    26. return obj;  

    解决C#结构体数组间的转化的相关内容就向你介绍到这里,希望对你学习和了解解决C#结构体数组间的转化方法有所帮助。

  • 相关阅读:
    Codeforces 845E Fire in the City 线段树
    Codeforces 542D Superhero's Job dp (看题解)
    Codeforces 797F Mice and Holes dp
    Codeforces 408D Parcels dp (看题解)
    Codeforces 464D World of Darkraft
    Codeforces 215E Periodical Numbers 容斥原理
    Codeforces 285E Positions in Permutations dp + 容斥原理
    Codeforces 875E Delivery Club dp
    Codeforces 888F Connecting Vertices 区间dp (看题解)
    Codeforces 946F Fibonacci String Subsequences dp (看题解)
  • 原文地址:https://www.cnblogs.com/wangjixianyun/p/3155892.html
Copyright © 2011-2022 走看看