So, the thing is that I have an array of double that I'd like to send to my C# application through a running C++ DLL (loaded by my C# app).
It seems that I should be using IntPtr or something like this to exchange arrays or string (array of chars) but I can't really figure out how to perfom it ...
Anyone could tell (+ example) some way to send "double[]" or "string" to/from C#/C++ code ?
Here is some piece of code as an example :
C#
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
delegate void FuncPtr([MarshalAs(UnmanagedType.LPArray)] ref double[] dblArr);
[DllImport(dllFilePath, CallingConvention = CallingConvention.Cdecl)]
public static extern void callCSharpFunctionDblArr(IntPtr fctPointer);
public static void printInConsoleDblArr(ref double[] nbArr)
{
Console.Write("value = ");
for(int i=0; i<nbArr.Length; i++)
Console.Write(nbArr[i] + "; ");
Console.WriteLine();
for (int i = 0; i < nbArr.Length; i++)
nbArr[i] = nbArr[i] + 1;
Console.Write("value = ");
for (int i = 0; i < nbArr.Length; i++)
Console.Write(nbArr[i] + "; ");
Console.WriteLine();
}
static void Main(string[] args)
{
FuncPtr printInConsoleDblArrDelegate =
new FuncPtr(printInConsoleDblArr);
IntPtr printInConsoleDblArrPtr =
Marshal.GetFunctionPointerForDelegate(printInConsoleDblArrDelegate);
Console.WriteLine("Second time called from C++ using the call back !!!");
callCSharpFunctionDblArr(printInConsoleDblArrPtr);
Console.ReadLine();
}
C++
__declspec(dllexport) void callCSharpFunctionDblArr( void *fctPointer(double*&) )
{
double* dbl = new double[5];
for(int i=0; i<5; i++)
dbl[i] = (0.5*i);
for(int i=0; i<5; i++)
std::cout << "Before :: dbl[" << i << "] = " << dbl[i] << std::endl;
fctPointer(dbl);
for(int i=0; i<5; i++)
std::cout << "After :: dbl[" << i << "] = " << dbl[i] << std::endl;
}
With this code, I get the following error ::
An unhandled exception of type 'System.AccessViolationException' occurred in ConsoleApplication1.exe
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.