下面的代码是被反映的形式.Net框架:为什么Marshal.WriteInt64方法的代码如此复杂?
[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
是不够的,非常有效的。
为什么这么复杂?
也许是与endiens? 。 – KingCronus 2012-07-16 08:57:49
看起来更像是与我的内存对齐。 – 2012-07-16 09:00:56
这是memcpy(),手工展开。我想,在ARM内核上是必需的。 – 2012-07-16 10:04:56