Dimensions of structures on 32-bit and 64-bit

In the .NET struct design guidelines , it gives a maximum reasonable structure size of 16 bytes. How do you determine how large your structure is and how the architecture in which your program works influences it? Is this value only 32-bit or for both arches?

+5
source share
3 answers

Yes, the size of the structure depends on the architecture. C # structures in 32 bits are aligned with 4 byte boundaries, and in 64-bit they are aligned in 8 bytes.

Example:

struct Foo
{
   int bar;
}

4 32- 8 64- , "int bar" 4 32- 64- .

Update:

. :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
    struct Bar
    {
        int a;
    }

    struct Foo
    {
        Uri uri;
        int a;
    }

    class Program
    {
        static void Main(string[] args)
        {
            Foo[] foo;
            long fooBefore = System.GC.GetTotalMemory(true);
            foo = new Foo[10];
            long fooAfter = System.GC.GetTotalMemory(true);

            Bar[] bar;
            long barBefore = System.GC.GetTotalMemory(true);
            bar = new Bar[10];
            long barAfter = System.GC.GetTotalMemory(true);

            Foo aFoo = new Foo();
            Bar aBar = new Bar();

            System.Console.Out.WriteLine(String.Format("[Foo] Size of array of 10: {0}, Marshal size of one: {1}", fooAfter - fooBefore, System.Runtime.InteropServices.Marshal.SizeOf(aFoo)));
            System.Console.Out.WriteLine(String.Format("[Bar] Size of array of 10: {0}, Marshal size of one: {1}", barAfter - barBefore, System.Runtime.InteropServices.Marshal.SizeOf(aBar)));
            System.Console.ReadKey();
        }
    }
}

64- , :

[Foo] Size of array of 10: 208, Marshal size of one: 16
[Bar] Size of array of 10: 88, Marshal size of one: 4

32- , :

[Foo] Size of array of 10: 92, Marshal size of one: 8
[Bar] Size of array of 10: 64, Marshal size of one: 4

:

  • , Bar, , 4 32- 64- .
  • , Foo, , 8 32 (4 int 4 Uri), 16 64 (4 int, 8 Uri, , 4 )
+3

, , . 24 32 , , , . - , 32 ( ..), ; .

, - , . ( IntPtr/UIntPtr), , . ( , .)

, . ?

+6

.Net 32 64- . 2 , , ,

  • IntPtr
  • UIntPtr

, .

, , ,

, , . 4 32- 8 64- .

+4

All Articles