簡體   English   中英

C# struct 或 struct[] 作為 memory 中連續結構的成員

[英]C# struct or struct[] as member of struct contiguous in memory

我試圖了解如何將結構作為結構的成員存儲在 memory 中。 據我了解,如果我們在 memory 中有一個簡單的結構,例如

struct Simple {
  int x;
  bool y;
}

那么如果我們在 memory 中初始化Simple s = new Simple()我們會看到類似

s(0x01) --> 0x01(x - 32 bits data, y - 32 bits data) 

因此,如果我們調用sx ,那么我們需要將s提取到 cpu 中,然后可以訪問 x 和 y 進行操作,因為它們是連續的。

現在,如果我們有一個結構數組作為成員

struct Simple {
  int x;
  Other[] otherArray;

  Simple(int input, Other[] otherInput)
  {
    x = input;
    otherArray = otherInput;
  }
}

struct Other {
  bool y;
}

如果我們做Simple s = new Simple()那么在 memory 我們會有

s(0x01) --> 0x01(x - 32 bits, otherArray - 64 bit reference type) 

s.otherArray[0]存儲在 memory 中的任何位置都需要單獨獲取。 這是因為otherArray中的實際值不與x連續存儲,但對數據的引用在x之后是連續的。 如果otherArray被初始化為Simple s = new Simple(1, new Simple[1])otherArray數據是否會在 x 之后連續存儲,或者otherArray總是以任何方式作為引用類型(無論它是否在結構構造函數中初始化) )?

最后,如果我們有一個結構體作為結構體的成員

struct Simple {
  int x;
  Other other;
}

這是我不清楚的地方。 Is Simple s = new Simple()現在存儲為

s(0x01) --> 0x01(x - 32 bits data, other - 32 bits data of y as bool)

或者是

s(0x01) --> 0x01(x - 32 bits, other - some reference to the data containing y as bool)

換句話說,一個結構是作為結構的成員與結構連續存儲的,還是簡單地存儲為另一個結構的實際數據的某種地址?

我還希望對我的邏輯進行任何更正或進一步了解不同類型如何存儲在結構中的 memory 中,因為我試圖大致了解 C# 如何將數據存儲在 memory 中,謝謝,

otherArray數據是否會在x之后連續存儲,或者otherArray總是以任何方式作為引用類型

otherArray始終是對數組 object 的引用,即使它只有一個元素。 結構布局是結構類型的屬性,而不是特定結構值的屬性。

結構是作為結構成員的結構與結構連續存儲還是簡單地存儲為其他結構的實際數據的某種地址?

結構是值類型,因此沒有“其他結構的實際數據的某種地址”。 這就是引用類型的作用。 它不一定是連續的,(但在OtherSimple的情況下是連續的) - 如果您未指定顯式PackLayoutKind ,它將遵循默認的 alignment 規則。 請參閱此處了解更多信息。

讓我們考慮一下:

struct Simple
{
    public int x;
    public Other other;
}

struct Other
{
    public int y;
}

和價值:

var s = new Simple();
s.x = unchecked((int)0xabcdefab);
s.other.y = 0x12345678;

您希望s的大小為 8 個字節,其值將包含數字0xabcdefab0x12345678

// prints 8
Console.WriteLine(sizeof(Simple));
// in an unsafe block, prints 12345678ABCDEFAB
Console.WriteLine(Marshal.ReadInt64(new IntPtr(&s)).ToString("X"));

您可以嘗試向Other添加更多字段,並看到sizeof(Simple)增加

將此與引用類型進行比較:

struct Simple
{
    public int x;
    public OtherRef other;
}

class OtherRef
{
    public int y;
}

您現在不能使用&來獲取地址,所以這里有一個sharplab鏈接來顯示other字段確實是一個地址,而不是您設置的值。

暫無
暫無

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

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