This is where you did wrong. You are returning a pointer to an array of pointers. You got the first correct one by actually reading the value of the pointer from the array. But then your for () loop got it wrong, just adding 4 (or 8) to the first pointer value. Instead of reading them from an array. Fix:
IntPtr[] ptrs = new IntPtr[numHumans]; // Populate the array of IntPtr for (int i = 0; i < numHumans; i++) { ptrs[i] = (IntPtr)Marshal.PtrToStructure(humansPtr, typeof(IntPtr)); humansPtr = new IntPtr(humansPtr.ToInt64() + IntPtr.Size); }
Or much cleaner, since marshaling of arrays of simple types is already supported:
IntPtr[] ptrs = new IntPtr[numHumans]; Marshal.Copy(humansPtr, ptrs, 0, numHumans);
I found the error using Debug + Windows + Memory + Memory 1. Put peoplePtr in the Address field, switching to a 4-byte integer representation and noticing that the C code is doing it right. Then it quickly became clear that ptrs [] does not contain the values ββthat I saw in the memory window.
Not sure why you are writing such code other than mental exercise. This is the wrong way to do this, for example, you completely ignore the need to release memory again. This is very nontrivial. Parsing CSV files in C # is pretty simple and as fast as in C, it is an I / O binding, not an execution. You can easily avoid these almost impossible debugging errors and get a lot of help from the .NET Framework.
source share