本人使用c# socket 接收回来的数据是byte数组,我需要把它转换成结构体?
结构体定义public struct head
    {
        public ushort Command;
        public int DataLen;  
    };网上搜索了转换方法 /// <summary>
    /// byte数组转换为结构体
    /// </summary>
    /// <param name="bytes"></param>
    /// <param name="type"></param>
    /// <returns></returns>
    public static object BytesToStuct(byte[] bytes, Type type)
    {
        //得到结构体的大小
        int size = System.Runtime.InteropServices.Marshal.SizeOf(type);
        //byte数组长度小于结构体的大小
        if (size > bytes.Length)
        {
            //返回空
            return null;
        }
        //分配结构体大小的内存空间
        IntPtr structPtr = System.Runtime.InteropServices.Marshal.AllocHGlobal(size);
        //将byte数组拷到分配好的内存空间
        System.Runtime.InteropServices.Marshal.Copy(bytes, 0, structPtr, size);
        //将内存空间转换为目标结构体
        object obj = System.Runtime.InteropServices.Marshal.PtrToStructure(structPtr, type);
        //释放内存空间
        System.Runtime.InteropServices.Marshal.FreeHGlobal(structPtr);
        //返回结构体
        return obj;
    }我调用时候这样 byte[] datas = new byte[1024];
            int bytes = 0;
            while (true)//循环接受数据
            {
                bytes = client.Receive(datas);
                if (bytes <= 0)
                {
                    break;
                }
            }
            head heads=new head();
            heads=BytesToStuct(datas,head);这样调用报错 error CS0118: '_Default.head' is a 'type' but is used like a 'variable'
 error CS1502: The best overloaded method match for '_Default.BytesToStuct(byte[], System.Type)' has some invalid arguments
 error CS1503: Argument '2': cannot convert from '_Default.head' to 'System.Type'怎么搞定啊?

解决方案 »

  1.   

    你网是找的那个是内存转换的,你是要实现Socket 收到的数据转换Struct吗?,那你自己定义的Struct, 再接发消息时,都要按照这样的结构来操作 ,发的是二进制序列,我记得有个序列化,和反序列化,来转化的,好长时间没看了,你自己再搜索一下
      

  2.   

    网上的答案是
     head heads=new head();
     heads=BytesToStuct(datas,head);
    不能直接把结构类型赋给函数BytesToStuct(datas,head);需要转换成System.Type类型
    “我在测试时,发现将字节数组转换成结构体时,有错。
    后来发现是在参数type的赋值上有错。因为我是直接把结构体的类型赋值过去,报错说不能把类型当做变量。
    之后用typeof(),把结构体转换成System.Type类型后才成功了。”
      

  3.   

    方法是没有错的,结构体需要加上
    [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
        public struct UDP_data
        {
            public ulong time_now; //定义探头采样的时间
            public UInt32 ID;  //设备的唯一ID
            public UInt32 feedback; //反馈状态, BIT0 – BIT4 有效,分别代表反馈1-反馈5,1为反馈开启
      

  4.   

    heads=BytesToStuct(datas,head);改为:
    heads=(head)BytesToStuct(datas,typeof(head));