假設我有一個byte []數組,我想知道什麼,我真的這樣做時,我做的指針數組,然後將其轉換爲int。當我取消引用說INT指針,我得到的情況下波紋管數量較多:(代碼可能有錯誤)基本鑄造的問題(C#)
byte[] bytes = new byte[100];
bytes[0] = 1;
bytes[1] = 2;
bytes[2] = 3;
bytes[3] = 4;
fixed (byte* pMem = &bytes[0])
{
Debug.WriteLine("{0:x16}", (int)pMem);
byte* pMemPlus1 = pMem + 1;
Debug.WriteLine("{0:x8}", *pMemPlus1);
byte* pMemPlus2 = pMem + 2;
Debug.WriteLine("{0:x16}", *pMemPlus2);
int* pArrayBase = (int*) pMem;
Debug.WriteLine("{0:x8}", *pArrayBase);
int* pArrayBasePlus1 = pArrayBase+1;
Debug.WriteLine("{0:x8}", *pArrayBasePlus1;
}
權,從而預期值Pmem,PMemPlus1和PMemPlus2提領1,2和3(詮釋)pMem我拿它是指針(內存地址)的值。
但是,當它作爲一個int指針強制轉換時,pArrayBase給出了4030201,pArrayBasePlus1給出了數字4.後者是有意義的,因爲int是4個字節長。但我不明白。當我只取消引用int-cast數組指針(pArrayBase)時的結果。任何解釋?我可能無法理解正確投射的概念。
這是很容易創建的代碼,由於轉換錯誤故障,如果你把它寫在C.不要讓生活困難的自己,如果這是你的目標。用較少的諷刺(不難實現),你爲什麼要演員? –
基本上我一直在經歷本教程:geekswithblogs.net/robp/archive/2008/08/13/speedy-c-part-3-understanding-memory-references-pinned-objects-and.aspx –
注意,鑄造指向int的指針在32位機器上只是一個明智的事情。如果你有一個64位的進程,那麼你必須投入很長時間。你可能會考慮鑄造IntPtr的,這是保證是大小爲指針同一個結構。 –