2012-01-17 86 views
4

是否有可能以某種方式強制轉換由fixed()語句創建的指針的類型?將C#字節數組固定爲int指針

情況是這樣的:

我有字節,這是我想遍歷的陣列,但是我想的值被視爲INT,因此具有一個int *而不是字節* 。

下面是一些示範代碼:

byte[] rawdata = new byte[1024]; 

fixed(int* ptr = rawdata) //this fails with an implicit cast error 
{ 
    for(int i = idx; i < rawdata.Length; i++) 
    { 
     //do some work here 
    } 
} 

這可以無需做迭代中投來完成?

+2

爲什麼你要在C#中使用指針?爲了迭代這個,你可以簡單地使用'for'循環。 – 2012-01-17 11:35:27

+0

同意。雖然從一開始就添加您的意圖有助於提供答案並避免問題:) – Timo 2016-02-02 14:11:07

回答

4
byte[] rawdata = new byte[1024]; 

fixed(byte* bptr = rawdata) 
{ 
    int* ptr=(int*)bptr; 
    for(int i = idx; i < rawdata.Length; i++) 
    { 
     //do some work here 
    } 
} 
+0

是的,謝謝。當然。 – WhiteN01se 2012-01-17 14:57:37

+0

你實際上並沒有移動你的指針,這可能是一個好主意。你還應該提到字節大小的差異。 – Guvante 2012-01-18 22:16:53

5

我相信你有通過一個byte*。例如:

using System; 

class Test 
{ 
    unsafe static void Main() 
    { 
     byte[] rawData = new byte[1024]; 
     rawData[0] = 1; 
     rawData[1] = 2; 

     fixed (byte* bytePtr = rawData) 
     { 
      int* intPtr = (int*) bytePtr; 
      Console.WriteLine(intPtr[0]); // Prints 513 on my box 
     } 
    } 
} 

注意迭代時,你應該使用rawData.Length/4,不rawData.Length如果你對待你的字節數組作爲32位值的序列。

+0

是的,我相信你對.Length/4是正確的。 – WhiteN01se 2012-01-18 22:00:13

+0

用指針算術處理任何剩餘字節的最佳方法是什麼,它不會均勻地劃分成sizeof(int)? (例如,如果字節數組長度爲1023字節。) – 2012-02-23 11:41:44

+0

@QuickJoeSmith:基本上,我可能會使用指針算術處理這些* not *。 – 2012-02-23 11:54:43

2

我找到了 - 貌似 - 更優雅,做這樣的一些原因,也更快捷的方式:

 byte[] rawData = new byte[1024]; 
     GCHandle rawDataHandle = GCHandle.Alloc(rawData, GCHandleType.Pinned); 
     int* iPtr = (int*)rawDataHandle.AddrOfPinnedObject().ToPointer(); 
     int length = rawData.Length/sizeof (int); 

     for (int idx = 0; idx < length; idx++, iPtr++) 
     { 
      (*iPtr) = idx; 
      Console.WriteLine("Value of integer at pointer position: {0}", (*iPtr)); 
     } 
     rawDataHandle.Free(); 

這樣,我需要做的唯一的事情 - 從設置正確的迭代長度分開 - 是增量指針。我將代碼與使用固定語句的代碼進行了比較,而且這個代碼稍快。