码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2017-08-26 15:07:25      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:ring   使用   obj   oba   struct   private   orm   pack   type   

//结构体的定义

[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"
            }

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

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

标签:ring   使用   obj   oba   struct   private   orm   pack   type   

原文地址:http://www.cnblogs.com/JackMo/p/7435288.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!