C#: convert generic pointer to array

前端 未结 5 1672
长发绾君心
长发绾君心 2021-01-03 14:29

I want to convert a byte* to a byte[], but I also want to have a reusable function to do this:

public unsafe static T[] Create

        
5条回答
  •  感情败类
    2021-01-03 14:47

    How about this?

    static unsafe T[] MakeArray(void* t, int length, int tSizeInBytes) where T:struct
    {
        T[] result = new T[length];
        for (int i = 0; i < length; i++)
        {
            IntPtr p = new IntPtr((byte*)t + (i * tSizeInBytes));
            result[i] = (T)System.Runtime.InteropServices.Marshal.PtrToStructure(p, typeof(T));
        }
    
        return result;
    }
    

    We can't use sizeof(T) here, but the caller can do something like

    byte[] b = MakeArray(pBytes, lenBytes, sizeof(byte));
    

提交回复
热议问题