1

I am working on project that required to pass array of objects from c# to c++ by reference and when I pass one object by reference it return by the new value successfully but when I pass an array it return with the old value so what is wrong with my code?

C++ code

extern "C" __declspec(dllexport) int solve(Cell*(&xx)[5][5]) {
xx[0][0]->side = 55;
return xx[0][0]->side;
}

and C# code

internal static class UnsafeMethods
{
[DllImport(@"E:\Cs\4th Year\HPC\Parallel_calculations\Debug\Parallel_calculations.dll", EntryPoint = "solve", CallingConvention = CallingConvention.Cdecl)]
public static extern int solve([MarshalAs(UnmanagedType.SafeArray)] ref Cell[,] x);
}

 Cell[,] arr = new Cell[5, 5];
        for (int i = 0; i < arr.GetLength(0); i++)
        {
            for (int y = 0; y < arr.GetLength(1); y++)
            {
                arr[i, y] = new Cell(0, 0, 0, false, false, false, 50);
            }
        }
        arr[0, 0].side = 4;
        int x = UnsafeMethods.solve(ref arr);
        Console.WriteLine(x + " " + arr[0, 0].side);

x is with new value but arr[0,0].side return with old value

10
  • Possible duplicate of Pass multi - dimensional array from managed code to unmanaged code Commented Dec 22, 2016 at 18:53
  • no i can send it arleady but without reference ! Commented Dec 22, 2016 at 18:58
  • I am not sure that one can correctly pass multidimensional array to native function other then by how it is described in the linked question, but I may be wrong. In any case, arrays by themselves are passed as [In] parameters - msdn.microsoft.com/en-us/library/z6cfh6e6(v=vs.110).aspx. So you should at least try to add [InOut] attribute on the array parameter. If that won't work, then you should try the proposed solution and then manually reconstruct the array - stackoverflow.com/questions/6747112/… Commented Dec 22, 2016 at 19:05
  • till now no one of the two answers solve my problem and i can only pass the array by value !, any help Commented Dec 22, 2016 at 20:02
  • Another problem with your code is that you specify UnmanagedType.SafeArray, but the C++ code is using a reference to an array (basically a pointer to pointer to the first element of the array). The correct C++ type to use is the SAFEARRAY structure. Otherwise, leave the C++ code as is, and specify UnmanagedType.LPArray in C#. Also, as the other poster mentioned, arrays are always marshaled as one-dimensional between managed and unmanaged code. Commented Dec 22, 2016 at 21:10

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.