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
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));