简体   繁体   English

在不安全的C#中使用指向数组的指针

[英]Using pointer to array in unsafe C#

In C, I can define a pointer to an array like this: 在C中,我可以像这样定义一个指向数组的指针:

char b1[SOME_SIZE];
char (*b3)[3]=(char(*)[3])b1;

so that b3[i][j] == b1[i*3+j] . 所以b3[i][j] == b1[i*3+j]

Can I declare such a pointer, b3 , in unsafe C#? 我可以在unsafe C#中声明这样的指针b3吗?

My intention is to access bitmap channels as: 我的目的是访问位图通道:

///...
unsafe {
    //...
    byte *target; //8bpp
    byte (*source)[3]; //24bpp
    //...
    target[x]=(source[x][0]+source[x][1]+source[x][2])/3;
    //...

I hope this way, using source[x][ch] instead of source[x*3+ch] to get some compiler optimization. 我希望这样,使用source[x][ch]而不是source[x*3+ch]来获得一些编译器优化。

[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct FastPixel
{
    public readonly byte R;
    public readonly byte G;
    public readonly byte B;
}


private static void Main()
{
    unsafe
    {
        // 8-bit.
        byte[] b1 =
        {
            0x1, 0x2, 0x3,
            0x6, 0x7, 0x8,
            0x12, 0x13, 0x14
        };


        fixed (byte* buffer = b1)
        {
            var fastPixel = (FastPixel*) buffer;
            var pixelSize = Marshal.SizeOf(typeof (FastPixel));

            var bufferLength = b1.Length / pixelSize;
            for (var i = 0; i < bufferLength; i++)
            {
                Console.WriteLine("AVERAGE {0}", (fastPixel[i].R + fastPixel[i].G + fastPixel[i].B)/pixelSize);
            }
        }
    }
}

} }

This should be pretty much identical what you have. 这应该与你拥有的几乎相同。 Note that I don't expect any performance gains. 请注意,我不希望任何性能提升。 This is not micro-optimization, it's nano-optimization. 这不是微优化,而是纳米优化。

If dealing with huge images, look into parallel programming & SSE and how cache lines work(they have saved me actually 3-4 seconds - crazy right?!) 如果处理巨大的图像,请查看并行编程和SSE以及缓存线的工作方式(他们实际上已经节省了3-4秒 - 疯了吗?!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM