C#——Marshal.StructureToPtr方法簡介


目錄

  1. MarshalStructureToPtr方法簡介
  2. 功能及位置
  3. 語法
  4. 參數說明
  5. 異常
  6. 備注
  7. 舉例
本博客( http://blog.csdn.net/livelylittlefish)貼出作者(三二一、小魚)相關研究、學習內容所做的筆記,歡
迎廣大朋友指正!
                                            
                                            
具體可以參考 http://msdn.microsoft.com
                                            
                                            

Marshal.StructureToPtr方法簡介

                                            
                                            

1. 功能及位置

                                            
                                            
將數據從托管對象封送到非托管內存塊,屬於.NET Framework 類庫
命名空間:System.Runtime.InteropServices
程序集:mscorlib(在 mscorlib.dll 中)
                                            
                                            

2. 語法

                                            
                                            
C#:
      [ComVisibleAttribute(true)] public static void StructureToPtr (Object structure,IntPtr ptr,bool fDeleteOld);
C++:
      [ComVisibleAttribute(true)]public: static void StructureToPtr (Object^ structure, IntPtr ptr, bool fDeleteOld);
                                            
                                            

3. 參數說明

                                            
                                            
structure:托管對象,包含要封送的數據。該對象必須是格式化類的實例。
ptr:指向非托管內存塊的指針,必須在調用此方法之前分配該指針。
fDeleteOld:設置為 true 可在執行Marshal.DestroyStructure方法前對 ptr 參數調用此方法。請注意,傳遞 false 可導致內存泄漏。
                                            
                                            

4. 異常

                                            
                                            
異常類型:ArgumentException
條件:structrue參數是泛型類型
                                            
                                            

5. 備注

                                            
                                            
StructureToPtr將結構的內容復制到 ptr 參數指向的預分配內存塊。如果 fDeleteOld 參數為 true,則使用嵌入指
針上適當的刪除 API 來刪除最初由 ptr 指向的緩沖區,但該緩沖區必須包含有效數據。此方法為在鏡像托管類中指
定的每個引用字段執行清理工作。
                                            
假設 ptr 指向非托管內存塊。此內存塊的布局由相應的托管類 structure 描述。StructureToPtr將字段值從結構封
送到指針。假設 ptr 塊包含引用字段,該字段指向當前包含“abc”的字符串緩沖區。假設托管端上相應的字段是包含“vwxyz”的字符串。如果不另行通知它,StructureToPtr將分配一個新的非托管緩沖區來保存“vwxyz”,並將它掛鈎到 ptr 塊。這將丟棄舊緩沖區“abc”使之漂移而不將其釋放回非托管堆。最后,您將得到一個孤立的緩沖區,它表示在代碼中存在內存泄漏。如果將 fDeleteOld 參數設置為真,則 StructureToPtr 在繼續為“vwxyz”分配新緩沖區之前釋放保存“abc”的緩沖區。
                                            
                                            

6. 舉例

                                            
                                            
定義PERSON結構,並將該結構的一個變量拷貝到非托管內存,再將該內存中的PERSON還原為PERSON對象,觀察其內容的變化。
                                            
                                            
源代碼如下:
using System;
using System.Text;
using System.Runtime.InteropServices;

namespace testStructureToPtr
{
    public static class define  //define some constant
    {        
        public const int MAX_LENGTH_OF_IDENTICARDID = 20;   //maximum length of identicardid
        public const int MAX_LENGTH_OF_NAME = 50;           //maximum length of name
        public const int MAX_LENGTH_OF_COUNTRY = 50;        //maximum length of country
        public const int MAX_LENGTH_OF_NATION = 50;         //maximum length of nation
        public const int MAX_LENGTH_OF_BIRTHDAY = 8;        //maximum length of birthday
        public const int MAX_LENGTH_OF_ADDRESS = 200;       //maximum length of address
    }

    public struct PERSON    //person structure
    {
        //MarshalAs:指示如何在托管代碼和非托管代碼之間封送數據
        //UnmanagedType:指定如何將參數或字段封送到非托管內存塊
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = define.MAX_LENGTH_OF_IDENTICARDID)]
        public byte[] identicardid;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = define.MAX_LENGTH_OF_NAME)]
        public byte[] name;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = define.MAX_LENGTH_OF_COUNTRY)]
        public byte[] country;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = define.MAX_LENGTH_OF_NATION)]
        public byte[] nation;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = define.MAX_LENGTH_OF_BIRTHDAY)]
        public byte[] birthday;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = define.MAX_LENGTH_OF_ADDRESS)]
        public byte[] address;
    }

    class testProgram
    {
        private static byte _fillChar = 0;      //the fill character

        //convert string to byte array in Ascii with length is len        
        public static byte[] CodeBytes(string str, int len)
        {
            if (string.IsNullOrEmpty(str))
            {
                str = string.Empty;
            }
 
            byte[] result = new byte[len];
            byte[] strBytes = Encoding.Default.GetBytes(str);

            //copy the array converted into result, and fill the remaining bytes with 0
            for (int i = 0; i < len; i++)
                result[i] = ((i < strBytes.Length) ? strBytes[i] : _fillChar);
            
            return result;
        }

        //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));
        }

        static void Main(string[] args)
        {
            PERSON person;
            person.identicardid = CodeBytes("123456198001011111", define.MAX_LENGTH_OF_IDENTICARDID);
            person.name = CodeBytes("jackson", define.MAX_LENGTH_OF_NAME);
            person.country = CodeBytes("China", define.MAX_LENGTH_OF_COUNTRY);
            person.nation = CodeBytes("HanZu", define.MAX_LENGTH_OF_NATION);
            person.birthday = CodeBytes("19800101", define.MAX_LENGTH_OF_BIRTHDAY);
            person.address = 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:");
            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:");
                ShowPerson(anotherPerson);
            }
            catch (ArgumentException)
            {
                throw;
            }
            finally
            {
                Marshal.FreeHGlobal(intPtr);    //free tha memory
            }
        }
    }
}
運行過程中的對象地址及其內容如下:
                                            
                                            
intPtr指向的內存塊的內容就是程序中對person對象所賦的初值,如下圖所示,共計378個字節:
 
對象person和another的地址及其identicardid成員的地址:
 
 
對象person的identicardid成員的內容,即程序中的值123456198001011111,最后的2個字節為0,圖中顯示的是20個元素的ASCII碼的16進制數值:
 
運行結果如下:
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM