固定int指针的C#字节数组
本文关键字:字节 字节数 数组 int 指针 固定 | 更新日期: 2023-09-27 18:20:44
是否可以以某种方式强制转换fixed()语句创建的指针类型?
情况如下:
我有一个字节数组,我想对其进行迭代,但我希望这些值被视为int,因此使用int*而不是byte*。
以下是一些示例代码:
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
}
}
这可以在不必在迭代中进行强制转换的情况下完成吗?
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
}
}
我认为您必须通过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
}
}
}
请注意,在迭代时,如果将字节数组视为32位值的序列,则应使用rawData.Length / 4
,而不是rawData.Length
。
我发现了一种看起来更优雅、出于某种原因也更快的方法:
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();
这样,除了设置正确的迭代长度之外,我唯一需要做的就是增加指针。我将代码与使用fixed语句的代码进行了比较,这个代码稍微快一些。