Search code examples
c#c++arrayspinvoke

Returning a variable sized array of doubles from C++ to C# - a simpler way?


I have the following C++ method :

__declspec(dllexport) void __stdcall getDoubles(int *count, double **values); the method allocates and fills an array of double and sets *count to the size of the array.

The only way i managed to get this to work via pinvoke is :

[System.Runtime.InteropServices.DllImportAttribute("xx.dll")]
 public static extern void getDoubles(ref int count, ref System.IntPtr values);

and usage is :

int count = 0;
IntPtr doubles = new IntPtr();
Nappy.getDoubles(ref count, ref doubles);
double[] dvs = new double[count];
for(int i = 0;i < count;++{
    dvs[i] = (double)Marshal.PtrToStructure(doubles, typeof(System.Double));
    doubles = new IntPtr(doubles.ToInt64()+Marshal.SizeOf(typeof(System.Double)));
}

the values end up in the dvs array. Is there a better way ti do this not invloving pointer arithmetic in a managed language...


Solution

  • I think you can use

    Marshal.Copy( source, destination, 0, size );