The memory layout (layout) and size (size) zt of the struct instance field in the. NET hosting environment

Source: Internet
Author: User
The memory layout (layout) and size (size) of the struct instance field in the. NET hosting environment)


In C/C ++, once the members of the struct type are declared, the layout order of the members in the instance is determined, that is, it is in the same order as the member declaration, and in the default
In this case, align is always aligned based on the Members who occupy the largest space in the structure. Of course, we can also set the memory alignment mode by setting or encoding, memory alignment in C/C ++
For more information, see my previous interview notes.Summary: The questions about setting memory alignment were not answered during the interview.

However. net hosting environment, CLR provides a more free way to control layout in struct: We can use the structlayoutattribute feature on struct to control the memory layout of Members when defining struct.By default, the layout order of fields in the struct instance is the same as that in the declaration.[Structlayoutattribute (layoutkind. Sequential)] is used on struct.Structures are commonly used and unmanagedCodeInteraction.
If we are creating a struct type that does not have any interoperability with the non-hosted code, we may want to change this default rule of the C # compiler, so layoutkind
In addition to sequential members, there are two members: auto and explicit, which are passed to structlayoutattribute.Layoutkind. Auto allows CLR to arrange the fields in the instance in the optimal way they have chosen.; InputLayoutkind. Explicit allows the field to set the field sorting method more flexibly according to the fieldoffset we set on the field.But this method is also quite dangerous. If you set an error, the consequences will be severe. Let's take a few examples to calculate the number of bytes each of the four struct sets?

1. [structlayout (layoutkind. Sequential)]

Struct Structdeft // C # The Compiler automatically uses [structlayout (layoutkind. Sequential)]
... {
BoolI;//1 byte
DoubleC;//8 byte
BoolB;//1 byte
}


The result of sizeof (structdeft) is 24 bytes! Aha, only 10 bytes of data occupies 24 bytes of memory, because the default
(Layoutkind. Sequential), the CLR's layout Processing Method for struct is the same as the default Processing Method in C/C ++, that is, according to the structure
Align ). 10 bytes of data occupies 24 bytes, which seriously wastes the memory. Therefore, if we are creating an unmanaged code, there is no
It is recommended that you do not use the default structlayoutattribute (layoutkind. Sequential) feature for struct type interoperability.

2. [structlayout (layoutkind. explicit)]

[Structlayout (layoutkind. explicit)]
Struct Badstruct
... {
[Fieldoffset ( 0 )]
Public   Bool I; // 1 byte
[Fieldoffset ( 0 )]
Public   Double C; // 8 byte
[Fieldoffset ( 0 )]
Public   Bool B; // 1 byte
}


The result of sizeof (badstruct) is 9 bytes. Obviously, Base 9 shows that CLR does not align the struct with any memory (align ).
10 bytes only account for 9 bytes of data, and some of the data is obviously lost, which is why I named struct badstruct. If you use it on struct
[Structlayout (layoutkind. explicit)]. Be careful when calculating fieldoffset. For example, we use the above
Badstruct to perform the following test:

Structexpt E =   New Structexpt ();
E. c =   0 ;
E. I =   True ;
Console. writeline (E. C );

The output is no longer 0, but 4.94065645841247e-324, because E. C and E. I share the same byte and execute "E. I = true; "also changed E. c. The CPU is parsing according to the floating point format E. c. (For details about floating point numbers, refer toAccurately determine whether a floating point number is equal to 0).So when using layoutkind. explicit, do not forget fieldoffset :)

3. [structlayout (layoutkind. Auto)]

The result of sizeof (structauto) is 12 bytes. Next we will test how the three fields of structauto are placed:

Unsafe
... {
Structauto s =   New Structauto ();
Console. writeline ( String . Format ( " I: {0} " ,( Int ) & (S. I )));
Console. writeline ( String . Format ( " C: {0} " ,( Int ) & (S. C )));
Console. writeline ( String . Format ( " B: {0} " ,( Int ) & (S. B )));
}
// Test results:
I: 1242180
C: 1242172
B: 1242181

That is, the CLR will adjust the field sequence in the struct. After I is adjusted to C, the structauto instance s occupies as little memory as possible and align the 4 byte memory ), shows the field sequence adjustment result:

4. Empty struct instance size

Struct Emptystruct ... {}

The sizeof (emptystct) obtained by using explicit, auto, and sequential of layoutkind above is 1 byte.

Conclusion:

Default (Layoutkind. SequentialIn this case, the CLR's layout Processing Method for struct is the same as the default Processing Method in C/C ++, that isAlign);

UseLayoutkind. ExplicitIn this case,CLR does not align the struct with any memory (align)And we should be careful that it is fieldoffset;

UseLayoutkind. AutoIn this case, CLR will adjust the field order in the struct so that the instance occupies as little memory as possible, andAlign ). 

Happyhippy

Author: silent void
Source: http://happyhippy.cnblogs.com/
This statement must be retained and stated inArticleThe source text link is provided at the starting position.


In C/C ++, once the members of the struct type are declared, the layout order of the members in the instance is determined, that is, it is in the same order as the member declaration, and in the default
In this case, align is always aligned based on the Members who occupy the largest space in the structure. Of course, we can also set the memory alignment mode by setting or encoding, memory alignment in C/C ++
For more information, see my previous interview notes.Summary: The questions about setting memory alignment were not answered during the interview.

However. net hosting environment, CLR provides a more free way to control layout in struct: We can use the structlayoutattribute feature on struct to control the memory layout of Members when defining struct.By default, the layout order of fields in the struct instance is the same as that in the declaration.[Structlayoutattribute (layoutkind. Sequential)] is used on struct.Structures are often used for interaction with unmanaged code..
If we are creating a struct type that does not have any interoperability with the non-hosted code, we may want to change this default rule of the C # compiler, so layoutkind
In addition to sequential members, there are two members: auto and explicit, which are passed to structlayoutattribute.Layoutkind. Auto allows CLR to arrange the fields in the instance in the optimal way they have chosen.; InputLayoutkind. Explicit allows the field to set the field sorting method more flexibly according to the fieldoffset we set on the field.But this method is also quite dangerous. If you set an error, the consequences will be severe. Let's take a few examples to calculate the number of bytes each of the four struct sets?

1. [structlayout (layoutkind. Sequential)]

Struct Structdeft // C # The Compiler automatically uses [structlayout (layoutkind. Sequential)]
... {
BoolI;//1 byte
DoubleC;//8 byte
BoolB;//1 byte
}


The result of sizeof (structdeft) is 24 bytes! Aha, only 10 bytes of data occupies 24 bytes of memory, because the default
(Layoutkind. Sequential), the CLR's layout Processing Method for struct is the same as the default Processing Method in C/C ++, that is, according to the structure
Align ). 10 bytes of data occupies 24 bytes, which seriously wastes the memory. Therefore, if we are creating an unmanaged code, there is no
It is recommended that you do not use the default structlayoutattribute (layoutkind. Sequential) feature for struct type interoperability.

2. [structlayout (layoutkind. explicit)]

[Structlayout (layoutkind. explicit)]
Struct Badstruct
... {
[Fieldoffset ( 0 )]
Public   Bool I; // 1 byte
[Fieldoffset ( 0 )]
Public   Double C; // 8 byte
[Fieldoffset ( 0 )]
Public   Bool B; // 1 byte
}


The result of sizeof (badstruct) is 9 bytes. Obviously, Base 9 shows that CLR does not align the struct with any memory (align ).
10 bytes only account for 9 bytes of data, and some of the data is obviously lost, which is why I named struct badstruct. If you use it on struct
[Structlayout (layoutkind. explicit)]. Be careful when calculating fieldoffset. For example, we use the above
Badstruct to perform the following test:

Structexpt E =   New Structexpt ();
E. c =   0 ;
E. I =   True ;
Console. writeline (E. C );

The output is no longer 0, but 4.94065645841247e-324, because E. C and E. I share the same byte and execute "E. I = true; "also changed E. c. The CPU is parsing according to the floating point format E. c. (For details about floating point numbers, refer toAccurately determine whether a floating point number is equal to 0).So when using layoutkind. explicit, do not forget fieldoffset :)

3. [structlayout (layoutkind. Auto)]

The result of sizeof (structauto) is 12 bytes. Next we will test how the three fields of structauto are placed:

Unsafe
... {
Structauto s =   New Structauto ();
Console. writeline ( String . Format ( " I: {0} " ,( Int ) & (S. I )));
Console. writeline ( String . Format ( " C: {0} " ,( Int ) & (S. C )));
Console. writeline ( String . Format ( " B: {0} " ,( Int ) & (S. B )));
}
// Test results:
I: 1242180
C: 1242172
B: 1242181

That is, the CLR will adjust the field sequence in the struct. After I is adjusted to C, the structauto instance s occupies as little memory as possible and align the 4 byte memory ), shows the field sequence adjustment result:

4. Empty struct instance size

Struct Emptystruct ... {}

The sizeof (emptystct) obtained by using explicit, auto, and sequential of layoutkind above is 1 byte.

Conclusion:

Default (Layoutkind. SequentialIn this case, the CLR's layout Processing Method for struct is the same as the default Processing Method in C/C ++, that isAlign);

UseLayoutkind. ExplicitIn this case,CLR does not align the struct with any memory (align)And we should be careful that it is fieldoffset;

use layoutkind. when auto is used, CLR adjusts the field sequence in the struct so that the instance occupies as little memory as possible, and align ).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.