IntPtr Address increment (not value)

1.2k Views Asked by At

I have a C++ DLL which has got functions to send data from a device. From my managed C# code i call the C++ function positionCallback. Here notice the pos. pos as per definition-is Array of three pointers, pointing to arrays of positions.

public void positionCallback(uint devNo,uint count,uint index,ref System.IntPtr pos,ref System.IntPtr mrk)

Now my issue is i want to extract the data of each of those 3 arrays but i can only get the data for Array 1 and for rest 2 i am getting garbage value. Below is the code i am trying

 // Copy the unmanaged array to managed memory for Axis 2
IntPtr ptr2 = IntPtr.Add(pos,2*sizeof(Int64));
 Marshal.Copy(pos,managedArrayAxis1,0,(int)count);
 // Copy the unmanaged array to managed memory for Axis 2
 Marshal.Copy(ptr2, managedArrayAxis2, 0, (int)count);

Above code is giving correct data only for managedArrayAxis1 but for managedArrayAxis2, garbage data is collecting. Am i wrongly incrementing IntPtr address for pos?

Please help!

1

There are 1 best solutions below

2
On BEST ANSWER

That pos parameter is actually a pointer to an array of pointers to double arrays so you need to dereference it twice. What's happening with your code is that the ref automatically dereferences the pointer to array of pointers but what you're getting in pos is just the first pointer out of 3 second level pointers and no way to get to the other two.

To get the original pointer you need to remove the ref keyword on pos parameter. Then copy the data pointed to by pos into an array of IntPtrs and you won't need any pointer arithmetic:

public void positionCallback(uint devNo,uint count,uint index,System.IntPtr pos,ref System.IntPtr mrk)

// copy the array of pointers
IntPtr[] arrays = new IntPtr[3];
Marshal.Copy(pos, arrays, 0, 3);

// Copy the unmanaged array to managed memory for Axis 2
Marshal.Copy(arrays[0],managedArrayAxis1,0,(int)count);

// Copy the unmanaged array to managed memory for Axis 2
Marshal.Copy(arrays[1], managedArrayAxis2, 0, (int)count);