C# 对结构体和指针的使用

//结构体的定义

[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
        public struct VGAStat
        {
            public int length;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
            public int[] number;
        }

public struct VGAStat1
        {
            public string str;
            public IntPtr intptr1;//指针的定义
        }

private void Form1_Load(object sender, EventArgs e)
        {

/********初始化结构体VGAStat*****************/
            VGAStat pp = new VGAStat();   
            pp.length = 123;
            pp.number=new int[6];
            for (int i = 0; i < 6; i++)
            {
                pp.number[i] = i + 1;
            }

   /**************************************************/

IntPtr intpt = Marshal.AllocHGlobal(Marshal.SizeOf(pp));   //对intpt分配内存
            Marshal.StructureToPtr(pp, intpt, true); 将数据封送到intpt

   /********初始化结构体VGAStat1*****************/

VGAStat1 vga = new VGAStat1();
            vga.intptr1 = intpt;

   /**************************************************/

VGAStat entries = (VGAStat)Marshal.PtrToStructure(vga.intptr1, typeof(VGAStat));

/********读取结构体数据*****************/
            string Number = string.Empty;

int ReadLength = entries.length;        //ReadLength=132
            for (int i = 0; i < 6; i++)
            {
                Number = Number + entries.number[i].ToString(); //Number="123456"
            }

/**************************************************/

上一篇:Java-集合框架总结


下一篇:NSIS(001)检测和结束进程是否运行?