简体   繁体   English

获取存储为对象的数组的第一个元素的地址

[英]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. 我需要获取任意类型数组的第一个元素的内存地址,该数组存储为一种Object类型。 For instance the array could be a double[] or an int[], but in the code it will be typed as an Object. 例如,数组可以是double []或int [],但在代码中它将被键入为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#. 虽然直接获取已知类型的数组的地址,但在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? 是否有一个类型(除了Object)我可以用来存储这样一个数组,并且可以更容易地获得其内存地址? Or is there a way to use Interop/Reflection to access the address directly without need for an intermediate data copy? 或者有没有办法使用Interop / Reflection直接访问地址而无需中间数据副本?

Notice in the second line below that a double[] is stored as an object. 请注意,在下面的第二行中,double []存储为对象。 And notice in the fixed() line that I am trying to obtain the address of o, which is not allowed in C#. 并注意在fixed()行中我试图获取o的地址,这在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...
                }

    }

You can achieve this using GCHandle : 您可以使用GCHandle实现此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. 只要确定你真的需要这个。

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

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