Getting Array of struct from IntPtr

前端 未结 3 1309
囚心锁ツ
囚心锁ツ 2020-12-10 02:47

I have some struct like this

struct MyStruct
{
    public int field1;
    public int field2;
    public int field3;
}

and I have pointer to

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-10 03:45

    This function worked for me, assuming that the size of the struct is fixed:

    public static void MarshalUnmananagedArray2Struct(IntPtr unmanagedArray, int length, out T[] mangagedArray)
    {
        var size = Marshal.SizeOf(typeof(T));
        mangagedArray = new T[length];
    
        for (int i = 0; i < length; i++)
        {
            IntPtr ins = new IntPtr(unmanagedArray.ToInt64() + i * size);
            mangagedArray[i] = Marshal.PtrToStructure(ins);
        }
     }
    

提交回复
热议问题