簡體   English   中英

獲取存儲為對象的數組的第一個元素的地址

[英]Obtain address of first element of an array stored as an object

我需要獲取任意類型數組的第一個元素的內存地址,該數組存儲為一種Object類型。 例如,數組可以是double []或int [],但在代碼中它將被鍵入為Object。

雖然直接獲取已知類型的數組的地址,但在C#中不允許獲取對象的地址。 是否有一個類型(除了Object)我可以用來存儲這樣一個數組,並且可以更容易地獲得其內存地址? 或者有沒有辦法使用Interop / Reflection直接訪問地址而無需中間數據副本?

請注意,在下面的第二行中,double []存儲為對象。 並注意在fixed()行中我試圖獲取o的地址,這在C#中是不允許的。

提前致謝!

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...
                }

    }

您可以使用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();
    }
}

只要確定你真的需要這個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM