我有一些在标准C#应用程序中使用的代码。
我正在在Silverlight项目中共享这个库,但Silverlight不允许使用不安全的代码。我对不安全/指针逻辑/算术一无所知,想知道是否有人能够将以下代码片段翻译成不需要使用/unsafe的代码,虽然客户端很少调用该代码,但我不关心性能下降。感谢您提前的帮助。
public static unsafe int GeStableHash(string name)
{
fixed (char* str = name)
{
char* chPtr = str;
int num = 352654597;
int num2 = num;
int* numPtr = (int*)chPtr;
for (int i = name.Length; i > 0; i -= 4)
{
num = (((num << 5) + num) + (num >> 27)) ^ numPtr[0];
if (i <= 2)
{
break;
}
num2 = (((num2 << 5) + num2) + (num2 >> 27)) ^ numPtr[1];
numPtr += 2;
}
return (num + (num2 * 1566083941));
}
}
根据下面的回复,我查看了此函数的Silverlight实现。
现在我更加困惑了。在SL mscorlib.dll的string.GetHashCode函数中,我看到的代码如下(它使用了unsafe关键字,并在Visual Studio中出现语法错误!):
[SecuritySafeCritical, ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public unsafe override int GetHashCode()
{
IntPtr arg_0F_0;
IntPtr expr_06 = arg_0F_0 = this;
if (expr_06 != 0)
{
arg_0F_0 = (IntPtr)((int)expr_06 + RuntimeHelpers.OffsetToStringData);
}
char* ptr = arg_0F_0;
int num = 352654597;
int num2 = num;
int* ptr2 = (int*)ptr;
int i;
for (i = this.Length; i > 2; i -= 4)
{
num = ((num << 5) + num + (num >> 27) ^ *ptr2);
num2 = ((num2 << 5) + num2 + (num2 >> 27) ^ ptr2[(IntPtr)4 / 4]);
ptr2 += (IntPtr)8 / 4;
}
if (i > 0)
{
num = ((num << 5) + num + (num >> 27) ^ *ptr2);
}
return num + num2 * 1566083941;
}
解决方案可以在这里找到: https://codereview.stackexchange.com/questions/7661/c-unsafe-code-translation。