2012-01-17 88 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(); 

这样,我需要做的唯一的事情 - 从设置正确的迭代长度分开 - 是增量指针。我将代码与使用固定语句的代码进行了比较,而且这个代码稍快。