Search code examples
c#.netreflectionmanagedunsafe

Obtain address of first element of an array stored as an object


I need to obtain the memory address of the first element of an array of arbitrary type, which is stored as a type of Object. For instance the array could be a double[] or an int[], but in the code it will be typed as an Object.

While it is straightforward to obtain the address of an array of known type, obtaining an address of an object is not allowed in C#. Is there a type (other than Object) that I could use to store such an array and whose memory address can be more easily obtained? Or is there a way to use Interop/Reflection to access the address directly without need for an intermediate data copy?

Notice in the second line below that a double[] is stored as an object. And notice in the fixed() line that I am trying to obtain the address of o, which is not allowed in C#.

Thanks in advance!

int len=100;
object o = new double [len];

   unsafe
   {
                fixed(int*ptr=&o)
                for (int index = 0; index < len; index++)
                {
                  // access data directly to copy it, etc...
                }

    }

Solution

  • You can achieve this using GCHandle:

    int len=100;
    object x = new long[len];
    unsafe
    {
        var gch = GCHandle.Alloc(x, GCHandleType.Pinned);
        try
        {
            void* addr = (void*)gch.AddrOfPinnedObject();
            // do whatever you want with addr
        }
        finally
        {
            gch.Free();
        }
    }
    

    Just be sure that you really need this.