I have a array in my C++ app and I want to use it's pointer to create a C# array delegate from it without copying. So I could make it work from C# to C++ , C++ access the same array defined in C# but cannot make it work in reverse.
C# Code :
[DllImport("CppDll.dll",CallingConvention=CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.LPArray)]
public static extern int[] GetCppArray();
C++ Code :
int test_data[5] = { 12,60,55,49,26 };
extern "C" __declspec(dllexport) int* GetCppArray()
{
return test_data;
}
Using in C# :
int[] cpparray = NativeLib.GetCppArray();
And I get this error :
System.Runtime.InteropServices.MarshalDirectiveException: 'Cannot marshal 'return value': Invalid managed/unmanaged type combination.'
I know I can use memory writers to write directly to C++ memory with array pointer address.
It works if use the same MarshalAs(UnmanagedType.LPArray)
in parameter and pass a C# array to c++ but why it doesn't work in opposite action?
Note : My data is huge I really can't use any copy here.