예제 #1
0
 //show the person information
 public static void ShowPerson(PERSON person)
 {
     Console.WriteLine("cardid   :" + Encoding.ASCII.GetString(person.identicardid));
     Console.WriteLine("name     :" + Encoding.ASCII.GetString(person.name));
     Console.WriteLine("country  :" + Encoding.ASCII.GetString(person.country));
     Console.WriteLine("nation   :" + Encoding.ASCII.GetString(person.nation));
     Console.WriteLine("birthday :" + Encoding.ASCII.GetString(person.birthday));
     Console.WriteLine("address  :" + Encoding.ASCII.GetString(person.address));
 }
예제 #2
0
        public static void MarshalStructureToPtrTest()
        {
            PERSON person;

            person.identicardid = MarshalTestProgram.CodeBytes("123456198001011111", define.MAX_LENGTH_OF_IDENTICARDID);
            person.name         = MarshalTestProgram.CodeBytes("jackson", define.MAX_LENGTH_OF_NAME);
            person.country      = MarshalTestProgram.CodeBytes("China", define.MAX_LENGTH_OF_COUNTRY);
            person.nation       = MarshalTestProgram.CodeBytes("HanZu", define.MAX_LENGTH_OF_NATION);
            person.birthday     = MarshalTestProgram.CodeBytes("19800101", define.MAX_LENGTH_OF_BIRTHDAY);
            person.address      = MarshalTestProgram.CodeBytes("Luoshan Road, Shanghai", define.MAX_LENGTH_OF_ADDRESS);

            int    nSizeOfPerson = Marshal.SizeOf(person);
            IntPtr intPtr        = Marshal.AllocHGlobal(nSizeOfPerson);

            Console.WriteLine("The person infomation is as follows:");
            MarshalTestProgram.ShowPerson(person);

            try
            {
                //将数据从托管对象封送到非托管内存块,该内存块开始地址为intPtr
                Marshal.StructureToPtr(person, intPtr, true);

                //将数据从非托管内存块封送到新分配的指定类型的托管对象anotherPerson
                PERSON anotherPerson = (PERSON)Marshal.PtrToStructure(intPtr, typeof(PERSON));

                Console.WriteLine("The person after copied is as follows:");
                MarshalTestProgram.ShowPerson(anotherPerson);
            }
            catch (ArgumentException)
            {
                throw;
            }
            finally
            {
                Marshal.FreeHGlobal(intPtr);    //free tha memory
            }

            Console.ReadLine();
        }