Getting an array of structures from IntPtr

I have a structure like this

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

and I have a pointer to an array of this structure. So, I need to get an array from this pointer. I am trying to use Marshal.PtrToStructure, but I have a memory read error. This is my method:

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

So what am I doing wrong?

+7
source share
3 answers

Two problems. You use TCnt instead of MyStruct in a call to Marshal.SizeOf (). Your IntPtr arithmetic cannot work on a 64-bit machine, you must use IntPtr.ToInt64 () or use for (long).

Just an erroneous IntPtr or length, of course, is also possible. Use Debug + Windows + Memory + Memory 1 and put "pointerToStruct" in the "Address" field for basic verification.

+4
source

Structures in C and C # are not the same thing. One of the differences is that in C # you need to explicitly require that your structure be laid out sequentially. If you did not write [StructLayout(LayoutKind.Sequential)] or [StructLayout(LayoutKind.Explicit)] for your structure. I do not think you can manage it that way. Microsoft says PtrToStructure used to convert structures from unmanaged to managed memory

You should check to see if this adds attributes to your structure, if that still doesn’t help allocate memory using Marshal.AllocHGlobal(IntPtr) and use Marshal.Copy to initialize your structure, and then try using PtrToStructure . If this works, you cannot use PtrToStructure with managed memory

+2
source

This function worked for me, assuming the structure size is fixed :

 public static void MarshalUnmananagedArray2Struct<T>(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<T>(ins); } } 
+1
source

All Articles