int _DataSize = Marshal.SizeOf(typeof(StatisticalData));
                IntPtr _DataIntPtr = Marshal.AllocHGlobal(_DataSize);
                Marshal.Copy(buff, _ClientHeadSize, _DataIntPtr, _DataSize);
                StatisticalData _CStatDataOBject = (StatisticalData)Marshal.PtrToStructure(_DataIntPtr, typeof(StatisticalData));
                Marshal.FreeHGlobal(_DataIntPtr);
_CStatDataOBject.connectionsSoFar等于0x0000000100000001
但是在buff里面看到的确是1啊,为啥变了呢

解决方案 »

  1.   

    定位问题,ClientHeadSize可能不对using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Runtime.InteropServices;namespace WindowsFormsApplication2
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();            byte[] buff = new byte[17];
                int _ClientHeadSize = 1;            buff[0] = (byte)'!';            buff[1] = (byte)'H';
                buff[2] = (byte)'E';
                buff[3] = (byte)'A';
                buff[4] = (byte)'D';            buff[5] = 0x12;            buff[6] = (byte)'O';
                buff[7] = (byte)'T';
                buff[8] = (byte)'H';
                buff[9] = (byte)'E';
                buff[10] = (byte)'R';
                buff[11] = (byte)'S';            int _DataSize = Marshal.SizeOf(typeof(StatisticalData));
                IntPtr _DataIntPtr = Marshal.AllocHGlobal(_DataSize);
                Marshal.Copy(buff, _ClientHeadSize, _DataIntPtr, _DataSize);
                StatisticalData _CStatDataOBject = (StatisticalData)Marshal.PtrToStructure(_DataIntPtr, typeof(StatisticalData));
                Marshal.FreeHGlobal(_DataIntPtr);            MessageBox.Show(new String(_CStatDataOBject.Other1)); // HEAD
                MessageBox.Show("0x" + _CStatDataOBject.B.ToString("x")); // 0x12
                MessageBox.Show(new String(_CStatDataOBject.Other2)); // OTHERS
            }        [StructLayout(LayoutKind.Sequential)]
            struct StatisticalData
            {
                [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
                public Char[] Other1;            [MarshalAs(UnmanagedType.I1)]
                public byte B;            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
                public Char[] Other2;
            }
        }
    }