gpt4 book ai didi

c# - 使用 LayoutKind.Explicit 绕过 "unsafe"指针是否合法?

转载 作者:太空宇宙 更新时间:2023-11-03 13:41:10 24 4
gpt4 key购买 nike

我有代码使用指针对数据 block 进行异或,速度很快,但我想摆脱对程序集的“不安全”要求。如果我将其更改为使用 LayoutKind.Explicit 并将“ulong[]”覆盖在“byte[]”之上,我基本上在做与指针相同的事情,但它似乎同样危险。这两者之间的主要区别在于“安全”版本的速度大约是“不安全”版本的 1/2。

这是绕过“不安全”程序集的合法方法,还是一次访问 byte[] 1 个字节是安全执行此操作的唯一合法方法?

private unsafe static void UnsafeEncode(
byte[] buffer, int bufPos, ulong[] vector, int SectionLength, byte vectorIndex)
{
fixed (byte* p = &buffer[bufPos])
{
ulong* pCur = (ulong*)p;
ulong* pEnd = pCur + SectionLength;
while (pCur < pEnd)
{
*pCur ^= vector[vectorIndex++];
pCur++;
}
}
}

[StructLayout(LayoutKind.Explicit)]
private struct ArrayOverlay
{
[FieldOffset(0)]
public byte[] Bytes;
[FieldOffset(0)]
public ulong[] Longs;
}

private static void SafeEncode(
byte[] buffer, int bufPos, ulong[] vector, int SectionLength, byte vectorIndex)
{
var overlay = new ArrayOverlay { Bytes = buffer };
int shiftleft = (bufPos & 7) << 3;
int pos = bufPos >> 3;
if (shiftleft == 0)
{
for (int i = 0; i < SectionLength; i++)
overlay.Longs[i + pos] ^= vector[vectorIndex++];
}
else
{
int shiftright = (64 - shiftleft) & 63;
ulong oldVec = 0;
for (int i = 0; i < SectionLength; i++)
{
var vec = vector[vectorIndex++];
overlay.Longs[i + pos] ^= (vec << shiftleft) | (oldVec >> shiftright);
oldVec = vec;
}
overlay.Longs[SectionLength + pos] ^= (oldVec >> shiftright);
}
}

最佳答案

Is this a legitimate way to get around having an "unsafe" assembly, or is accessing the byte[] 1 byte at a time the only legitimate way to do this in a safe manner?

这是合法的,因为它 1) 有效,并且 2) 可以产生正确的结果。

诚然,它不一定“安全”,因为您可以通过这样做来做“讨厌”的事情,但它仍然会起作用。在这种情况下,您肯定违反了安全代码的精神,因为您可以做“安全”代码中不允许的事情,例如有效地绕过数组长度检查并导致缓冲区溢出。

一次访问数组一个元素更符合“安全”代码的精神,但有时使用这样的技巧很有值(value),因为它提供了一种需要时的性能机制.如果您的特定场景需要性能,并且正常机制无法充分执行,这可能是一种使代码“工作”的方法,因为它满足您的规范(性能要求),而不会违反标记一个安全约束装配不安全。

关于c# - 使用 LayoutKind.Explicit 绕过 "unsafe"指针是否合法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16967146/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com