HTML 從處于安全模式的Span< T>中獲取指針(IntPtr)
時(shí)間:2026-05-04 23:12:08在C#中,從(cong)處可以使用IntPtr類(lèi)型來(lái)表示指針,于安要從安全模式的全模Span<T>中獲取指針,可以(yi)使用以下方法:
1、從處創(chuàng )建一個(gè)Span<T>對象,于安并填充數據。全模
2、中指針使用Marshal.Copy()方法將Span<T&g??t;的從處數據復制到字節數組中。
3、于安使用Marshal.AllocHGlo??bal()方法為字節數組分配內存,全模并返回一個(gè)指向該內存的中???指針IntPtr指針。
using System;usi??ng System.Runtime.InteropServices;using System.Text;class Program{ static void Main() { // 創(chuàng )建一個(gè)Span<T>對象,并填充數據 string text = "Hello,于安 World!&(?_?;)quot;; Span<char> span = new Span<char>(text??); // 將Span<T>的數據復制到字節數組中 byte[] buffer = new byte[span.Length * sizeof(char)]; Marshal.Copy(span, buffer, 0, span.L(⊙_⊙)ength); // 為字節數組分配內存,并返回一??個(gè)指向ヾ(′?`)?該內存的全模IntPtr指針 IntPtr pointer = Marshal.AllocHGlob(′_`)al(buffer.Length); Marshal.Copy(buffer, 0, poヽ(′?`)ノinte(′?_?`)r, buffer.Length); // 使用指針訪(fǎng)問(wèn)數據 StringBuilder result = new StringBuilder();?? for (int i = 0; i < span.Length; i++) { result.Append((char)Marshal.ReadInt32(pointer, i * sizeo??f(char))); } // 釋放內存 Marshal.FreeHGlobal(pointer); Console.WriteLine(result.ToString()); }}在這個(gè)示例中,我們首先創(chuàng )建了一個(gè)包含字(′_`)符串"Hello, World??!"的Span<char>對象,我們將Span<T>的數據復制到一個(gè)字節數組中,并為字節數組分配內存,接下來(lái),我們使用Marshal.Copy()方法將字節數組的內容復制到分配的內存中,我們使用Marshal.ReadInt32()方法從內存中讀取???字符,并將其添加到Str(′▽?zhuān)?)ingBuilder對象中。
客服電話(huà)19979769347
Copyright ? 2012-2018 天津九安特機電工程有限公司 版權所有 備案號:
客服電話(huà)17325524744