I can't seem to figure out how to return an array from an exported C++ DLL to my C# program. The only thing I've found from googling was using Marshal.Copy() to copy the array into a buffer but that doesn't give me the values I'm trying to return, I don't know what it's giving me.
Here's what I've been trying:
Exported function:
extern "C" __declspec(dllexport) int* Test()
{
int arr[] = {1,2,3,4,5};
return arr;
}
C# portion:
[DllImport("Dump.dll")]
public extern static int[] test();
static void Main(string[] args)
{
Console.WriteLine(test()[0]);
Console.ReadKey();
}
I know the return type int[] is probably wrong because of the managed/unmanaged differences, I just have no idea where to go from here. I can't seem to find an answer for anything but returning character arrays to strings, not integer arrays.
I figured the reason the values I'm getting with Marshal.Copy are not the ones I'm returning is because the 'arr' array in the exported function gets deleted but I'm not 100% sure, if anyone can clear this up that would be great.
I have implemented the solution Sriram has proposed. In case someone wants it here it is.
In C++ you create a DLL with this code:
The DLL will be called
InteropTestApp
.Then you create a console application in C#.
result
now contains the values1,2,3,4,5
.Hope that helps.