为什么Marshal.WriteInt64方法的代码如此复杂?

时间:2012-07-16 08:56:14

标签: c# marshalling unsafe

以下代码已反映在.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();
    }
}

在我看来,*((long*) numPtr) = val已经足够,效率很高。

为什么这么复杂?

1 个答案:

答案 0 :(得分:6)

虽然经过优化,但似乎相当简单。

注意外部的if - it检查你是否可以在一个操作中编写Int64(如果你传递方法的指针是正确对齐的话会发生这种情况 - 指向内存中Int64的开头 - 地址需要是是8的倍数。

如果你不能在一个操作中写入,代码只会一次写入一个字节,跳过循环以节省一些时间(这称为“循环展开”)