【问题标题】:C# byte array to fixed int pointerC#字节数组到固定的int指针
【发布时间】:2014-04-07 20:10:38
【问题描述】:

是否有可能以某种方式转换由 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
    }
}

无需在迭代中进行强制转换就可以做到这一点吗?

【问题讨论】:

  • 为什么要在 C# 中使用指针?要对此进行迭代,您可以简单地使用 for 循环。
  • 同意。尽管从一开始就添加您的意图有助于提供答案并避免问题:)

标签: c# pointers types casting


【解决方案1】:
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
    }
}

【讨论】:

  • 您实际上并没有移动指针,这可能是一个好主意。您还应该提到字节大小的差异。
【解决方案2】:

我相信你必须通过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

【讨论】:

  • 用指针算法处理任何剩余字节的最佳方法是什么,这些字节不能均匀地划分为sizeof(int)? (例如,如果字节数组的长度为 1023 字节。)
  • @QuickJoeSmith:基本上,我可能会用指针算法处理那些 not
【解决方案3】:

我发现了一种 - 看似 - 更优雅,并且出于某种原因也更快的方法:

        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();

这样,除了设置正确的迭代长度之外,我唯一需要做的就是增加指针。我将代码与使用固定语句的代码进行了比较,这个代码稍微快了一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-31
    • 2016-04-05
    • 1970-01-01
    • 2010-12-21
    • 2015-05-24
    • 2014-06-28
    相关资源
    最近更新 更多