好的,我想要做的基本想法是将字节数组转换为短或整数等。
一个简单的例子可能是:
unsafe
{
fixed (byte* byteArray = new byte[5] { 255, 255, 255, 126, 34 })
{
short shortSingle = *(short*)byteArray;
MessageBox.Show((shortSingle).ToString()); // works fine output is -1
}
}
好的,所以我真正想做的是,对 Stream 类进行扩展;扩展读写方法。我需要以下代码的帮助:
unsafe public static T Read<T>(this Stream stream)
{
int bytesToRead = sizeof(T); // ERROR: Cannot take the address of, get the size of, or declare a pointer to a managed type ('T')
byte[] buffer = new byte[bytesToRead];
if (bytesToRead != stream.Read(buffer, 0, bytesToRead))
{
throw new Exception();
}
fixed (byte* byteArray = buffer)
{
T typeSingle = *(T*)byteArray; // ERROR: Cannot take the address of, get the size of, or declare a pointer to a managed type ('T')
return typeSingle;
}
}
unsafe public static T[] Read<T>(this Stream stream, int count)
{
// haven't figured out it yet. This is where I read and return T arrays
}
我觉得我必须使用指针来提高速度,因为我将致力于从 NetworkStream 类等流中写入和读取数据。谢谢你的帮助!
编辑:
当我试图弄清楚如何返回 T 数组时,我遇到了这个问题:
unsafe
{
fixed (byte* byteArray = new byte[5] { 0, 0, 255, 255, 34 })
{
short* shortArray = (short*)byteArray;
MessageBox.Show((shortArray[0]).ToString()); // works fine output is 0
MessageBox.Show((shortArray[1]).ToString()); // works fine output is -1
short[] managedShortArray = new short[2];
managedShortArray = shortArray; // The problem is, How may I convert pointer to a managed short array? ERROR: Cannot implicitly convert type 'short*' to 'short[]'
}
}
总结:我必须从字节数组转换为给定类型的 T 或给定长度的给定类型的 T 数组