Getting Array of struct from IntPtr
Tengo una estructura como esta
struct MyStruct
{
public int field1;
public int field2;
public int field3;
}
y tengo puntero a la matriz de esta estructura. Entonces, necesito obtener una matriz de este puntero. Intenté usar Marshal.PtrToStructure, pero tuve un error de lectura de memoria. Este es mi método:
public MyStruct[] GetArrayOfStruct(IntPtr pointerToStruct, int length)
{
var sizeInBytes = Marshal.SizeOf(typeof(TCnt));
MyStruct[] output = new MyStruct[length];
for (int i = 0; i < length; i++)
{
IntPtr p = new IntPtr((pointerToStruct.ToInt32() + i * sizeInBytes));
output[i] = (MyStruct)System.Runtime.InteropServices.Marshal.PtrToStructure(p, typeof(MyStruct));
}
return output;
}
Entonces, ¿qué estoy haciendo mal?