Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing "this" pointer/reference using an indexer in C#

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];
        }
    }
}
like image 775
Kraken Avatar asked Nov 20 '25 05:11

Kraken


1 Answers

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];
}
like image 160
Groo Avatar answered Nov 22 '25 18:11

Groo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!