C# 擷取變數的指標(IntPtr)

來源:互聯網
上載者:User

標籤:zh-cn   輸出   sdn   microsoft   mars   asp   new   位元組   arp   

 1. 擷取數組的指標(IntPtr)

通過Marshal.UnsafeAddrOfPinnedArrayElement(Array,Int32)方法獲得一個數組的第某個元素的記憶體位址。

Array是數組,Int32是元素的索引,第一個元素是0。

例如:

int[] ary;

Intptr inp=Marshal..UnsafeAddrOfPinnedArrayElement(ary,0);

Console.Writleline(inp.Tostring());//輸出的就是一串數字,就是記憶體位址。

記憶體位址以位元組為單位,第一個元素地址為n,第二個為n+資料類型的位元組數。int32是4個位元組,那麼元素地相鄰址之間差4。

2.擷取某個變數的指標

這裡就要用到C#中的指標,用unsafe {}關鍵字,並設定【項目屬性】-【產生】-可以執行不安全的程式碼.

具體詳細資料見:https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/unsafe-code-pointers/

例如:

int ad;

unsafe

{

int* p=&ad; //建立指標P,指向變數ad

Console.Write((int)p); //ad的記憶體位址

Console.Write(*p); //引用p指向的資料,即ad

IntPtr op=new IntPtr((int)p);//構造c#類型的指標

Console.Write(Marshal.ReadInt32(op));//輸出的是變數ad的值

}

//跟指標p相關的變數只能出現在unsafe{}內部,外部無法使用

 

C# 擷取變數的指標(IntPtr)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.