3

I am experimenting with a datastructure for a performance / memory critical part of our codebase. I would like to have a fast access to the bytes defined in the structure. However I am not sure how to access the structure on which I am operating on using the indexer.

[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Foo
{
    [SerializeField]
    private byte a, b, c;

    public unsafe byte this[byte index]
    {
        get
        {       
            //omitted safety checks   

            //this is a no, no
            byte* addr = (byte*)&this;

            return addr[index];
        }
    }
}
Kraken
  • 295
  • 1
  • 3
  • 13

1 Answers1

5

You can only do what you're trying to do inside a fixed block, i.e.:

fixed (Foo* foo = &this)
{
    byte* addr = (byte*)foo;
    return addr[index];
}
vgru
  • 49,838
  • 16
  • 120
  • 201
  • Yes, I just got the syntax wrong when I tried it. Works like charm! Thank you! – Kraken Nov 07 '17 at 10:37
  • Well, that's what I want to measure :]. Also, if I would have used standard byte array, the size in memory is larger than the code above. – Kraken Nov 07 '17 at 10:50
  • I didn't even know you could do this in C#. I had figured there was probably a way, but this is the first I've seen. Cool – jleach Nov 07 '17 at 11:35