Array alignment in .NET

Are arrays in .NET tied to any border?

If so, for what? And the same for all types of arrays?

+4
source share
4 answers

Common Language Infrastructure (ECMA-335) sets the following alignment restrictions:

12.6.2 Alignment

The built-in data types must be properly aligned, which is defined as follows:

  • 1-byte, 2-byte, and 4-byte data are correctly aligned when they are stored at the 1-byte, 2-byte, or 4-byte boundary, respectively.
  • 8-byte data is correctly aligned when it is stored on the same boundary as is required for basic equipment for atomic access to the built-in int.

, int16 unsigned int16 ; int32, unsigned int32 float32 , 4; int64, unsigned int64 float64 , 4 8, . (native int, native unsigned int &) (4 8 , ). , , 8- . , float64 8- , native int 32 .

CLI , unaligned, . , JIT .

, CLI :

  • explicitlayout. , explicitlayout, / , , II.

...

. , , . , , , . : 1, 2, 4, 8 16. explicitlayout.

+7

, , () StructLayoutAttribute, , .

+2

, Microsoft BCL- , fixed . BitConverter.cs .NET 4.0:

    public static unsafe int ToInt32 (byte[]value, int startIndex) { 
        //... Parameter validation

        fixed( byte * pbyte = &value[startIndex]) {
            if( startIndex % 4 == 0) { // data is aligned
                return *((int *) pbyte); 
            }
            else { 
               // .. do it the slow way
            } 
        }
    } 

, startIndex, * pbyte. , :

  • pbyte .
  • .

, . ToInt32 , . BCL , CLR.

, , fixed .

0

.NET- ( ) (, 4 8 ). , .NET.

Michael Graczyk , , , Int32, 64- . 32- Int32 .

, , . 32- Int32. , .

, .NET . . * , long * :

unsafe
{
    var data = new byte[ 16 ];
    fixed ( byte* dataP = data )
    {
        var misalignedlongP = ( long* ) ( dataP + 3 );
        long value = *misalignedlongP;
    }
}

.NET, , Microsoft . System.Buffer.Memmove (. https://referencesource.microsoft.com/#mscorlib/system/buffer.cs,c2ca91c0d34a8f86). , * - , .

0

All Articles