struct SLPCI 
        {
            byte StartChar;
            byte Length;
            byte ControlArear;
        }
 SLPCI* LPCIHead; char[] sendbuf = new char[300]; LPCIHead = (SLPCI*)sendbuf;
LPCIHead->StartChar=68h;我想把初始化了的结构体存到数组sendbuf中,
这样写为什么不对啊?

解决方案 »

  1.   

        struct SLPCI
        {
            public byte StartChar;
            public byte Length;
            public byte ControlArear;        public SLPCI(byte i, byte j, byte k)
            {
                StartChar = i;
                Length = j;
                ControlArear = k;
            }
        } 
                int len = Marshal.SizeOf(typeof(SLPCI));
                SLPCI slp = new SLPCI(1,2,3);
                byte[] sendbuf = new byte[len];
                IntPtr ptr = Marshal.AllocHGlobal(len);
                Marshal.StructureToPtr(slp, ptr, true);
                Marshal.Copy(ptr, sendbuf, 0, len);
                Marshal.FreeHGlobal(ptr);
      

  2.   

                char[] buf = new char[300];
                unsafe
                {
                //char * buf=stackalloc char[300];
                    
                    fixed (char* pbuf = buf)
                    {
                        MyStruct* PStructDemo = (MyStruct*) pbuf;
                        PStructDemo->i = 1;
                        PStructDemo->j = 2;
                        PStructDemo->k = 3;
                    }
                }