C#: convert generic pointer to array

前端 未结 5 1688
长发绾君心
长发绾君心 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 15:09

    I have no idea whatsoever if the following would work, but it might (at least it compiles :):

    public unsafe static T[] Create(void* ptr, int length) where T : struct
    {
        T[] array = new T[length];
    
        for (int i = 0; i < length; i++)
        {
            array[i] = (T)Marshal.PtrToStructure(new IntPtr(ptr), typeof(T));
        }
    
        return array;
    }
    

    The key is to use Marshal.PtrToStructure to convert to the correct type.

提交回复
热议问题