我正在寻找一种方法来将 byte[] 类型的数组重新解释为另一种类型,比如 short[]。在 C++ 中,这将通过一个简单的强制转换来实现,但在 C# 中,我还没有找到一种方法来实现这一点而不诉诸于复制整个缓冲区。
有什么想法吗?
最佳答案
你可以做到这一点,但这是一个相对糟糕的主意。像这样的原始内存访问不是类型安全的,只能在完全信任的安全环境下进行。您永远不应在设计合理的托管应用程序中执行此操作。如果您的数据伪装成两种不同的形式,也许您实际上有两个独立的数据集?
无论如何,这里有一个快速简单的代码片段来完成您的要求:
byte[] bytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int byteCount = bytes.Length;
unsafe
{
// By using the fixed keyword, we fix the array in a static memory location.
// Otherwise, the garbage collector might move it while we are still using it!
fixed (byte* bytePointer = bytes)
{
short* shortPointer = (short*)bytePointer;
for (int index = 0; index < byteCount / 2; index++)
{
Console.WriteLine("Short {0}: {1}", index, shortPointer[index]);
}
}
}
关于c# - 在 C# 中重新解释_cast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/479705/