c#中Marshal.Copy()方法的使用

來源:互聯網
上載者:User

標籤:style   color   ar   使用   strong   sp   資料   on   ad   

c#中Marshal.Copy方法的使用

Marshal.copy()方法用來在託管對象(數組)和非託管對象(IntPtr)之間進行內容的複製

函數有很多重載,如下所示:

Copy(array<Byte>[]()[], Int32, IntPtr, Int32) 將一維的託管 8 位不帶正負號的整數數組中的資料複製到非託管記憶體指標。

Copy(array<Char>[]()[], Int32, IntPtr, Int32) 將資料從一維的託管字元數組複製到非託管記憶體指標。

Copy(array<Double>[]()[], Int32, IntPtr, Int32) 將資料從一維的託管雙精確度浮點數組複製到非託管記憶體指標。

Copy(array<Int16>[]()[], Int32, IntPtr, Int32) 將資料從一維的託管 16 位帶正負號的整數數組複製到非託管記憶體指標。

Copy(array<Int32>[]()[], Int32, IntPtr, Int32) 將資料從一維的託管 32 位帶正負號的整數數組複製到非託管記憶體指標。

Copy(array<Int64>[]()[], Int32, IntPtr, Int32) 將資料從一維的託管 64 位元帶正負號的整數數組複製到非託管記憶體指標。

Copy(IntPtr, array<Byte>[]()[], Int32, Int32) 將資料從非託管記憶體指標複製到託管 8 位不帶正負號的整數數組。

Copy(IntPtr, array<Char>[]()[], Int32, Int32) 將資料從非託管記憶體指標複製到託管字元數組。

Copy(IntPtr, array<Double>[]()[], Int32, Int32) 將資料從非託管記憶體指標複製到託管雙精確度浮點數組。

Copy(IntPtr, array<Int16>[]()[], Int32, Int32) 將資料從非託管記憶體指標複製到託管 16 位帶正負號的整數數組。

Copy(IntPtr, array<Int32>[]()[], Int32, Int32) 將資料從非託管記憶體指標複製到託管 32 位帶正負號的整數數組。

Copy(IntPtr, array<Int64>[]()[], Int32, Int32) 將資料從非託管記憶體指標複製到託管 64 位元帶正負號的整數數組。

Copy(IntPtr, array<IntPtr>[]()[], Int32, Int32) 將資料從非託管記憶體指標複製到託管 IntPtr 數組。

Copy(IntPtr, array<Single>[]()[], Int32, Int32) 將資料從非託管記憶體指標複製到託管單精確度浮點數組。

Copy(array<IntPtr>[]()[], Int32, IntPtr, Int32) 將資料從一維託管 IntPtr 數組複製到非託管記憶體指標。

Copy(array<Single>[]()[], Int32, IntPtr, Int32) 將資料從一維的託管單精確度浮點數組複製到非託管記憶體指標。

這裡需要注意的是兩個參數Int32類型的使用

Int32類型的兩個參數都是用來限定數組的,其中一個限定開始位置,一個限定長度

"xuwei";  

  • IntPtr pName = Marshal.AllocHGlobal(2*name.Length);  
  • Marshal.Copy(name.ToCharArray(), 0, pName, name.Length);  
  • char[] cName = new char[name.Length];  
  • Marshal.Copy(pName, cName, 0, name.Length);  

易知name.Length=5

(1) 給pName指標分配了2*name.Length位元組的空間

注意:Marshal.AllocHGlobal(Int32 cb)中的參數cb是分配的位元組數

(2) 將name轉換的char[]中的內容複寫到pName所指的記憶體中,所取長度為char的個數,即name.Length

(3) 給cName分配name.Length個char位置

(4) 將pName中的內容複寫到cName數組中,長度同樣為name.Length

c#中Marshal.Copy()方法的使用

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.