Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi,
I have a C function like this:

C++
double* foo() // function return array of 10 double
{
double* matrix  = (double *)malloc(10 * sizeof(double));
return matrix;
}


how can I write in the wrapper class? Should I do that?

C#
[DllImport("...")]
[return: MarshalAs(UnmanagedType..LPArray)]
public static extern double foo();


Please tell me the way.
Posted

1 solution

C#
[DllImport("...")]
public static extern IntPtr foo();

Should work. Then if you know the size of the array:
C#
IntPtr result = foo();
double[] arr = new double[10];
Marshal.Copy(result, arr, 0, 10);


If the array size isn't static, then you should return the size of the array like this:

C++
double* foo(int* size) // function return array of 10 double
{
double* matrix  = (double *)malloc(10 * sizeof(double));
*size = 10;
return matrix;
}

And use:
C#
[DllImport("...")]
public static extern IntPtr foo(out int size);

...

int size;
IntPtr result = foo(out size);
double[] arr = new double[size];
Marshal.Copy(result, arr, 0, size);
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900