通用类型指针?并将字节数组转换为给定类型的泛型?

hax*_*mer 9 c#

好吧,我正在尝试做的基本思路是将字节数组转换为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
            }
        }
Run Code Online (Sandbox Code Playgroud)

好的,所以我真正要做的是,对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
        }
Run Code Online (Sandbox Code Playgroud)

我觉得我必须使用指针来提高速度,因为我将致力于从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[]'
            }
        }
Run Code Online (Sandbox Code Playgroud)

总结:我必须从字节数组转换为给定类型的T OR到给定长度的给定类型的T数组

max*_*max 5

由于C#中的指针限制,您无法使此函数成为通用函数.以下任何类型都可以是指针类型:

  • sbyte,byte,short,ushort,int,uint,long,ulong,char,float,double,decimal或bool.
  • 任何枚举类型.
  • 任何指针类型.
  • 任何用户定义的结构类型,仅包含非托管类型的字段.

但是你不能对T设置限制where T <can be pointer type>.where T : struct非常接近,但还不够,因为用户定义的结构可以包含引用类型的字段.

有一种解决方法 - System.Runtime.InteropServices.Marshal.PtrToStructure()(如果它无法使用指定的对象类型,它只会引发异常),但它也会杀死任何已实现的性能改进.

我认为唯一的方法是为所有需要的类型创建非泛型函数.