Why is the code of the Marshal.WriteInt64 method so complicated?

Below is the code below .Net Framework:

[SecurityCritical]
public static unsafe void WriteInt64(IntPtr ptr, int ofs, long val){
    try{
        byte* numPtr = (byte*) (((void*) ptr) + ofs);
        if ((((int) numPtr) & 7) == 0){
            *((long*) numPtr) = val;
        }
        else{
            byte* numPtr2 = (byte*) &val;
            numPtr[0] = numPtr2[0];
            numPtr[1] = numPtr2[1];
            numPtr[2] = numPtr2[2];
            numPtr[3] = numPtr2[3];
            numPtr[4] = numPtr2[4];
            numPtr[6] = numPtr2[6];
            numPtr[7] = numPtr2[7];
        }
    }
    catch (NullReferenceException){
        throw new AccessViolationException();
    }
}

In my opinion, *((long*) numPtr) = valquite and very effective.

Why is it so complicated?

+5
source share
1 answer

It seems pretty simple, albeit optimized.

Pay attention to the external if - it checks whether you can write Int64 in one operation (what happens if the pointer to which you pass the method is aligned correctly - indicates the beginning of Int64 in memory - the address must be a multiple of 8).

If you cannot write in one operation, the code simply writes one byte at a time, skipping a loop to save some time (this is called a "loopback")

+6
source

All Articles