在C#中,從處可以使用In(╯°□°)╯tPtr類(lèi)型來(lái)表示指針,于安要從安全模式的全模S(╯‵□′)╯pan<(′_ゝ`)T>中獲取指針,可以使用以下方法:
1、從處創(chuàng )建一個(gè)Span<T>對象,于安并填充數據。全模
2、中指(zhi)針使用Mar(′ω`*)shal.Copy()方法將Span<T>的從處數據復制到字節(′_`)數組中。
3、于安使用Marshal.AllocHGlobal()方法為字節數組分配內存,全模并返回一個(gè)指向該內存的中指針IntPtr指針。
以下是從處一個(gè)示例代碼:
using System;using System.Runtime.InteropServices;using System.Text;clas??s Program{ static void Main() { // 創(chuàng )建一個(gè)Span<T>對象,并填充數據 string text = "Hello,于安 World!"; Span<char> span = new Span<char>(text); // 將Span<T>的數據復制到字節數組中 byte[] buffe(′?`*)r = new byte[span.Length * sizeof(char)]; Marshal.Copy(span, buffer, 0, span.Length); // 為字節數組分配內存,并返回一個(gè)指向該內存的全模(′?`)IntPtr指針 IntPtr pointer = Marshal.AllocHGlobal(buffer.Length); Marshal.Copy(buffer, 0, pointer, 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 * sizeof(char))); } // 釋放內存 Marshal.FreeHGl(′▽?zhuān)?)obal(poin???ter); Console.WriteLine(result.ToString()); }}在這個(gè)示例中,我們首先創(chuàng )建了一個(gè)(′_`)包含字符串"Hello, World!"的Span<char>對象,我們將Span<T>的數據復制到一個(gè)字節數組中,并為字節數組分(fen)配內存,接下來(lái),我們使用Marshal.Copy()方法?將字節數組的內(nei)容復制到分配的內存中,我們使用Marshal.ReadInt32()方法從內┐(′?`)┌存中讀取字符,并將其(qi)添加到StringBuilder對(dui)象中。
Copyright ? 2012-2018 天津九安特機電工程有限公司 版權所有 備案號: