Are arrays in .NET naturally aligned?

Does .NET provide any guarantee that .NET byte arrays are always correctly aligned? I need this for treatment, for example. an array of bytes in an insecure context like longs in x64 for changing pieces of data with its own register size.

But so far I have not found any documentation that the CLR gives me any guarantees that my memory access will be properly aligned.

+5
source share
2 answers

No. And in fact, arrays can be misaligned for x86 jitter. In particular, the problem with double [] and long [], the garbage collector provides a guarantee that they will be aligned to 4. What explains the special rule for double [], such an array will be allocated in a bunch of large objects when it has 1000 or more elements. Significantly less than the usual rule for LOH allocations of 85,000 or more bytes. LOH depends on the Windows Heap Alignment Guarantee aligned to 8. This is not a problem for x64 jitter.

: . , , . "" , Microsoft, , 4 , GC . - 4 x64, .

+6

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

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