好的,我尝试做的基本想法是,将字节数组转换为类似 short 或 int 等的东西。
一个简单的例子可能是:
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 数组
最佳答案
由于 C# 中的指针限制,您无法将此函数设为泛型。以下任何类型都可能是指针类型:
- sbyte、byte、short、ushort、int、uint、long、ulong、char、float、double、decimal 或 bool。
- 任何枚举类型。
- 任何指针类型。
- 任何仅包含非托管类型字段的用户定义结构类型。
但是你不能对Twhere T <can be pointer type>
设置限制. where T : struct
非常接近,但还不够,因为用户定义的结构可以包含引用类型的字段。
有一个解决方法 - System.Runtime.InteropServices.Marshal.PtrToStructure()
(如果它无法处理指定的对象类型,它只会抛出一个异常),但它也会扼杀任何已实现的性能改进。
我认为唯一的方法是为所有需要的类型创建非泛型函数。
关于c# - 通用类型指针?并将字节数组转换为给定类型的泛型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11726956/